2017-07-02 21 views
0

我有two component S和我需要從children component轉移stat e將parent component傳輸狀態從childComp到parentComp

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} 
} 

另一個有點棘手,這是我在父組件,它有兩個參數text and dateredux-action,總之,當我點擊按鈕,我需要從childComp轉移stateparentComp,然後創建兩個參數在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>; 
    } 
} 

你也可以使用reduxref