2017-07-02 9 views
0

、私はtwo component秒を持っていると私はparent component転送状態

class Parent Component { 
    this.state = {text: hahaha} 
    this.props.action(text, data) 

    <Children Component /> 
    <button onClick={this.props.action(text, data)} 
} 

class Children Component { 
    this.state = {date: 12.12.12} 
} 

children componentから、それは私は2つのパラメータtext and dateを取る親コンポーネントでredux-actionを持っています別の少しトリッキーをstat電子を転送する必要があります合計でボタンをクリックすると、statechildCompからparentCompに転送し、次に2つのパラメータを持つアクションをparentCompに作成する必要があります。だから、どうすればいいの?あなたが親コンポーネントに子の状態を取得することができます

答えて

2

Refer component communication

class Parent extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state = { 
      content: 'initial' 
     } 
     this.updateParentState = this.updateParentState.bind(this); 
    } 

    updateParentState(content){ 
     this.setState({ 
      content: content 
     }) 
    } 

    render(){ 
     let { content } = this.state; 
     return <div> 
      <Child updateParentState={this.updateParentState}/> 
      <h1>{ content }</h1> 
     </div> 
    } 
} 

class Child extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state = { 
      value: 'initial' 
     } 
     this.handleParentState = this.handleParentState.bind(this); 
     this.changeContent = this.changeContent.bind(this); 
    } 

    handleParentState(content){ 
     let { updateParentState } = this.props; 
     let { value } = this.state; 
     updateParentState(content); 
    } 

    changeContent(event){ 
     this.setState({ 
      value: event.target.value 
     }) 
    } 

    render(){ 
     let { value } = this.state 
     return <div> 
      <input value={value} onChange={this.changeContent}/> 
      <button onClick={this.handleParentState}>Update Parent State</button> 
     </div> 
    } 
} 
1

は、コールバックウィル:

class Parent extends React.Component{ 
    constructor(){ 
     super(); 
     this.state = { 

     }; 
    } 
    onClick(childState){ 
     console.log(childState); //see child state in parent component 
    } 
    render(){ 
     return <Child onClick={this.onClick} />; 
    } 
} 
class Child extends React.Component{ 
    constructor(){ 
     super(); 
     this.state = { 
      first: "first", 
      second: "second" 
     }; 
    } 
    render(){ 
     return <div onClick={() => this.props.onClick({...this.state})}>Click me</div>; 
    } 
} 

また、あなたはreduxまたはrefを使用することができます。

関連する問題