[javascript] ReactJS 호출 상위 메소드

ReactJS에서 첫 걸음을 내딛고 부모와 자녀 사이의 의사 소통을 이해하려고합니다. 양식을 만들고 있으므로 스타일 필드에 대한 구성 요소가 있습니다. 또한 필드를 포함하고 확인하는 부모 구성 요소가 있습니다. 예:

var LoginField = React.createClass({
    render: function() {
        return (
            <MyField icon="user_icon" placeholder="Nickname" />
        );
    },
    check: function () {
        console.log ("aakmslkanslkc");
    }
})

var MyField = React.createClass({
    render: function() {
...
    },
    handleChange: function(event) {
//call parent!
    }
})

그것을 할 수있는 방법이 있습니까? 그리고 내 논리는 reactjs “world”에 능숙한가? 시간 내 줘서 고마워.



답변

이를 위해 콜백을 속성으로 부모에서 자식으로 속성으로 전달합니다.

예를 들면 다음과 같습니다.

var Parent = React.createClass({

    getInitialState: function() {
        return {
            value: 'foo'
        }
    },

    changeHandler: function(value) {
        this.setState({
            value: value
        });
    },

    render: function() {
        return (
            <div>
                <Child value={this.state.value} onChange={this.changeHandler} />
                <span>{this.state.value}</span>
            </div>
        );
    }
});

var Child = React.createClass({
    propTypes: {
        value:      React.PropTypes.string,
        onChange:   React.PropTypes.func
    },
    getDefaultProps: function() {
        return {
            value: ''
        };
    },
    changeHandler: function(e) {
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(e.target.value);
        }
    },
    render: function() {
        return (
            <input type="text" value={this.props.value} onChange={this.changeHandler} />
        );
    }
});

위의 예에서 및 의 속성을 사용하여 Parent호출합니다 . 대가는 결합 표준에 핸들러 요소와에 값을 전달 의 콜백이 정의되어있는 경우.ChildvalueonChangeChildonChange<input />Parent

결과적으로 ParentchangeHandler메소드가 <input />필드 의 문자열 값인 첫 번째 인수와 함께 호출됩니다 Child. 결과는 Parent의 상태를 해당 값으로 업데이트 할 수 있으므로 입력 필드에 입력 <span />할 때 상위 요소가 새 값으로 업데이트됩니다 Child.


답변

모든 상위 메소드를 사용할 수 있습니다. 이를 위해 간단한 값처럼 부모에서 자녀 에게이 방법을 보내야합니다. 그리고 한 번에 부모로부터 많은 방법을 사용할 수 있습니다. 예를 들면 다음과 같습니다.

var Parent = React.createClass({
    someMethod: function(value) {
        console.log("value from child", value)
    },
    someMethod2: function(value) {
        console.log("second method used", value)
    },
    render: function() {
      return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);
    }
});

그리고 이것을 다음과 같이 Child에게 사용하십시오 (임의의 작업이나 모든 자식 메소드에).

var Child = React.createClass({
    getInitialState: function() {
      return {
        value: 'bar'
      }
    },
    render: function() {
      return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);
    }
});


답변

반응 16 이상 및 ES6으로 2019 업데이트

이것을 게시하는 것은 React.createClass반응 버전 16에서 더 이상 사용되지 않으며 새로운 Javascript ES6은 더 많은 이점을 제공합니다.

부모의

import React, {Component} from 'react';
import Child from './Child';

export default class Parent extends Component {

  es6Function = (value) => {
    console.log(value)
  }

  simplifiedFunction (value) {
    console.log(value)
  }

  render () {
  return (
    <div>
    <Child
          es6Function = {this.es6Function}
          simplifiedFunction = {this.simplifiedFunction}
        />
    </div>
    )
  }

}

아이

import React, {Component} from 'react';

export default class Child extends Component {

  render () {
  return (
    <div>
    <h1 onClick= { () =>
            this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
          }
        > Something</h1>
    </div>
    )
  }
}

ES6 상수로 단순화 된 stateless 자식

import React from 'react';

const Child = () => {
  return (
    <div>
    <h1 onClick= { () =>
        this.props.es6Function(<SomethingThatYouWantToPassIn>)
      }
      > Something</h1>
    </div>
  )

}
export default Child;


답변

의 방법에 합격 ParentA와 구성 요소 아래로 prop당신에 Child구성 요소를. 즉 :

export default class Parent extends Component {
  state = {
    word: ''
  }

  handleCall = () => {
    this.setState({ word: 'bar' })
  }

  render() {
    const { word } = this.state
    return <Child handler={this.handleCall} word={word} />
  }
}

const Child = ({ handler, word }) => (
<span onClick={handler}>Foo{word}</span>
)


답변

기능 사용 || 상태 비 저장 구성 요소

부모 구성 요소

 import React from "react";
 import ChildComponent from "./childComponent";

 export default function Parent(){

 const handleParentFun = (value) =>{
   console.log("Call to Parent Component!",value);
 }
 return (<>
           This is Parent Component
           <ChildComponent
             handleParentFun={(value)=>{
               console.log("your value -->",value);
               handleParentFun(value);
             }}
           />
        </>);
}

자식 컴포넌트

import React from "react";


export default function ChildComponent(props){
  return(
         <> This is Child Component
          <button onClick={props.handleParentFun("YoureValue")}>
            Call to Parent Component Function
          </button>
         </>
        );
}


답변

반응 16+

자식 컴포넌트

import React from 'react'

class ChildComponent extends React.Component
{
    constructor(props){
        super(props);
    }

    render()
    {
        return <div>
            <button onClick={()=>this.props.greetChild('child')}>Call parent Component</button>
        </div>
    }
}

export default ChildComponent;

부모 구성 요소

import React from "react";
import ChildComponent from "./childComponent";

class MasterComponent extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state={
            master:'master',
            message:''
        }
        this.greetHandler=this.greetHandler.bind(this);
    }

    greetHandler(childName){
        if(typeof(childName)=='object')
        {
            this.setState({
                message:`this is ${this.state.master}`
            });
        }
        else
        {
            this.setState({
                message:`this is ${childName}`
            });
        }

    }

    render()
    {
        return <div>
           <p> {this.state.message}</p>
            <button onClick={this.greetHandler}>Click Me</button>
            <ChildComponent greetChild={this.greetHandler}></ChildComponent>
        </div>
    }
}
export default  MasterComponent;


답변