[javascript] React에서 부모의 상태를 업데이트하는 방법은 무엇입니까?

내 구조는 다음과 같습니다.

Component 1

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5

Component 3

구성 요소 3은 구성 요소 5의 상태에 따라 일부 데이터를 표시해야합니다. 소품은 변경할 수 없으므로 단순히 구성 요소 1의 상태를 저장 한 다음 전달할 수 없습니다. 그리고 예, 나는 redux에 대해 읽었지만 그것을 사용하고 싶지 않습니다. 반응만으로 해결할 수 있기를 바랍니다. 내가 잘못?



답변

자녀-부모 의사 소통을 위해 다음과 같이 부모에서 자녀로 상태를 설정하는 함수를 전달해야합니다.

class Parent extends React.Component {
  constructor(props) {
    super(props)

    this.handler = this.handler.bind(this)
  }

  handler() {
    this.setState({
      someVar: 'some value'
    })
  }

  render() {
    return <Child handler = {this.handler} />
  }
}

class Child extends React.Component {
  render() {
    return <Button onClick = {this.props.handler}/ >
  }
}

이런 식으로 자식은 소품과 함께 전달 된 함수의 호출로 부모의 상태를 업데이트 할 수 있습니다.

그러나 구성 요소 5와 3은 관련이 없기 때문에 구성 요소의 구조를 재고해야합니다.

가능한 해결책 중 하나는 컴포넌트 1과 3의 상태를 모두 포함하는 상위 레벨 컴포넌트로 랩핑하는 것입니다.이 컴포넌트는 소품을 통해 하위 레벨 상태를 설정합니다.


답변

자식에서 부모 구성 요소로 onClick 함수 인수를 전달하는 다음 작업 솔루션을 찾았습니다.

메소드를 전달하는 버전 ()

//ChildB component
class ChildB extends React.Component {

    render() {

        var handleToUpdate  =   this.props.handleToUpdate;
        return (<div><button onClick={() => handleToUpdate('someVar')}>
            Push me
          </button>
        </div>)
    }
}

//ParentA component
class ParentA extends React.Component {

    constructor(props) {
        super(props);
        var handleToUpdate  = this.handleToUpdate.bind(this);
        var arg1 = '';
    }

    handleToUpdate(someArg){
            alert('We pass argument from Child to Parent: ' + someArg);
            this.setState({arg1:someArg});
    }

    render() {
        var handleToUpdate  =   this.handleToUpdate;

        return (<div>
                    <ChildB handleToUpdate = {handleToUpdate.bind(this)} /></div>)
    }
}

if(document.querySelector("#demo")){
    ReactDOM.render(
        <ParentA />,
        document.querySelector("#demo")
    );
}

JSFIDDLE을보십시오

화살표 함수를 전달하는 버전

//ChildB component
class ChildB extends React.Component {

    render() {

        var handleToUpdate  =   this.props.handleToUpdate;
        return (<div>
          <button onClick={() => handleToUpdate('someVar')}>
            Push me
          </button>
        </div>)
    }
}

//ParentA component
class ParentA extends React.Component {
    constructor(props) {
        super(props);
    }

    handleToUpdate = (someArg) => {
            alert('We pass argument from Child to Parent: ' + someArg);
    }

    render() {
        return (<div>
            <ChildB handleToUpdate = {this.handleToUpdate} /></div>)
    }
}

if(document.querySelector("#demo")){
    ReactDOM.render(
        <ParentA />,
        document.querySelector("#demo")
    );
}

JSFIDDLE을보십시오


답변

기본적으로 화살표 기능을 사용하여 내 문제에 대한 아이디어를 제공하고 하위 구성 요소에서 매개 변수를 전달한 것에 대한 가장 큰 대답을 고맙게 생각합니다.

 class Parent extends React.Component {
  constructor(props) {
    super(props)
    // without bind, replaced by arrow func below
  }

  handler = (val) => {
    this.setState({
      someVar: val
    })
  }

  render() {
    return <Child handler = {this.handler} />
  }
}

class Child extends React.Component {
  render() {
    return <Button onClick = {() => this.props.handler('the passing value')}/ >
  }
}

그것이 누군가를 돕기를 바랍니다.


답변

나는 함수를 전달하는 것에 대한 대답, 매우 편리한 기술을 좋아합니다.

반면 플럭스 와 마찬가지로 pub / sub 또는 변형 디스패처를 사용하여이를 달성 할 수도 있습니다 . 이론은 매우 간단합니다. 컴포넌트 5가 컴포넌트 3이 수신하는 메시지를 발송하도록합니다. 그런 다음 구성 요소 3은 상태를 업데이트하여 다시 렌더링을 트리거합니다. 이를 위해서는 관점에 따라 반 패턴 일 수도 있고 아닐 수도있는 상태 저장 구성 요소가 필요합니다. 나는 개인적으로 그들에 대항하고 있으며 다른 무언가가 파견을 듣고 있으며 하향식에서 상태를 변경하고 싶습니다 (Redux는 이것을하지만 추가 용어를 추가합니다).

import { Dispatcher } from flux
import { Component } from React

const dispatcher = new Dispatcher()

// Component 3
// Some methods, such as constructor, omitted for brevity
class StatefulParent extends Component {
  state = {
    text: 'foo'
  }

  componentDidMount() {
    dispatcher.register( dispatch => {
      if ( dispatch.type === 'change' ) {
        this.setState({ text: 'bar' })
      }
    }
  }

  render() {
    return <h1>{ this.state.text }</h1>
  }
}

// Click handler
const onClick = event => {
  dispatcher.dispatch({
    type: 'change'
  })
}

// Component 5 in your example
const StatelessChild = props => {
  return <button onClick={ onClick }>Click me</button>
}

Flux가 포함 된 디스패처 번들은 매우 간단합니다. 디스패치의 내용을 전달하여 디스패치가 발생할 때 콜백을 등록하고 호출합니다 (위의 간결한 예제에는 payload메시지 ID가 없음). 당신이 더 합리적이라면 전통적인 펍 / 서브 (예를 들어, 이벤트에서 EventEmitter를 사용하거나 다른 버전으로)에 이것을 쉽게 조정할 수 있습니다.


답변

param을 사용하여 자식에서 부모 구성 요소로 onClick 함수 인수를 전달하는 다음 작업 솔루션을 찾았습니다.

부모 클래스 :

class Parent extends React.Component {
constructor(props) {
    super(props)

    // Bind the this context to the handler function
    this.handler = this.handler.bind(this);

    // Set some state
    this.state = {
        messageShown: false
    };
}

// This method will be sent to the child component
handler(param1) {
console.log(param1);
    this.setState({
        messageShown: true
    });
}

// Render the child component and set the action property with the handler as value
render() {
    return <Child action={this.handler} />
}}

어린이 수업 :

class Child extends React.Component {
render() {
    return (
        <div>
            {/* The button will execute the handler function set by the parent component */}
            <Button onClick={this.props.action.bind(this,param1)} />
        </div>
    )
} }


답변

어떤 수준에서든 자녀와 부모 사이의 의사 소통이 필요할 때마다 context를 사용하는 것이 좋습니다 . 상위 컴포넌트에서 다음과 같이 하위에서 호출 할 수있는 컨텍스트를 정의하십시오.

사례 구성 요소 3의 상위 구성 요소

static childContextTypes = {
        parentMethod: React.PropTypes.func.isRequired
      };

       getChildContext() {
        return {
          parentMethod: (parameter_from_child) => this.parentMethod(parameter_from_child)
        };
      }

parentMethod(parameter_from_child){
// update the state with parameter_from_child
}

이제 하위 구성 요소 (귀하의 경우 구성 요소 5) 에서이 구성 요소에 부모의 컨텍스트를 사용하고 싶다고 알려주십시오.

 static contextTypes = {
       parentMethod: React.PropTypes.func.isRequired
     };
render(){
    return(
      <TouchableHighlight
        onPress={() =>this.context.parentMethod(new_state_value)}
         underlayColor='gray' >

            <Text> update state in parent component </Text>

      </TouchableHighlight>
)}

repo 에서 데모 프로젝트를 찾을 수 있습니다


답변

react가 단방향 데이터 흐름을 촉진함에 따라 부모에서 자식으로 만 데이터를 전달할 수 있지만 “자식 구성 요소”에서 무언가가 발생할 때 부모를 자체적으로 업데이트하기 위해 일반적으로 “콜백 함수”를 사용합니다.

부모에 정의 된 함수를 자식에 “props”로 전달하고 해당 함수를 자식 구성 요소에서 트리거하는 자식 함수에서 호출합니다.


class Parent extends React.Component {
  handler = (Value_Passed_From_SubChild) => {
    console.log("Parent got triggered when a grandchild button was clicked");
    console.log("Parent->Child->SubChild");
    console.log(Value_Passed_From_SubChild);
  }
  render() {
    return <Child handler = {this.handler} />
  }
}
class Child extends React.Component {
  render() {
    return <SubChild handler = {this.props.handler}/ >
  }
}
class SubChild extends React.Component {
  constructor(props){
   super(props);
   this.state = {
      somethingImp : [1,2,3,4]
   }
  }
  render() {
     return <button onClick = {this.props.handler(this.state.somethingImp)}>Clickme<button/>
  }
}
React.render(<Parent />,document.getElementById('app'));

 HTML
 ----
 <div id="app"></div>

이 예에서는 함수를 직계 Child에 전달하여 SubChild-> Child-> Parent에서 데이터를 전달할 수 있습니다.