2016-08-19 134 views
22

更改子組件的狀態,我有兩個組成部分: 父組件從中我想更改子組件的狀態:反應JS從父組件

class ParentComponent extends Component { 
    toggleChildMenu() { 
    ????????? 
    } 
    render() { 
    return (
     <div> 
     <button onClick={toggleChildMenu.bind(this)}> 
      Toggle Menu from Parent 
     </button> 
     <ChildComponent /> 
     </div> 
    ); 
    } 
} 

而且輔元件

class ChildComponent extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     open: false; 
    } 
    } 

    toggleMenu() { 
    this.setState({ 
     open: !this.state.open 
    }); 
    } 

    render() { 
    return (
     <Drawer open={this.state.open}/> 
    ); 
    } 
} 

我需要從父組件更改子組件的打開狀態,或者調用子組件t的toggleMenu()從父組件按鈕在父組件單擊時?

回答

41

該狀態應該在父組件中進行管理。您可以通過添加屬性將open值轉移到子組件。

class ParentComponent extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
     open: false 
     }; 

     this.toggleChildMenu = this.toggleChildMenu.bind(this); 
    } 

    toggleChildMenu() { 
     this.setState(state => ({ 
     open: !state.open 
     })); 
    } 

    render() { 
     return (
     <div> 
      <button onClick={this.toggleChildMenu}> 
       Toggle Menu from Parent 
      </button> 
      <ChildComponent open={this.state.open} /> 
     </div> 
     ); 
    } 
} 

class ChildComponent extends Component { 
    render() { 
     return (
     <Drawer open={this.props.open}/> 
    ); 
    } 
} 
+0

這能用來控制CSS屬性像 '顯示'?如果我的道具'open'包含'none'或'inline-block',css顯示道具是否會更新? – deusofnull

+1

yes試試看,它應該可以運行 –

+0

我最終使用react-classname軟件包,並使用'display'prop作爲布爾值來判斷是否向元素添加'hidden'類。這很容易,我的開發人員推薦我的方法。謝謝你的迴應! – deusofnull

2

上面的回答對我來說是完全正確的,但在我的情況,我想將值設置爲一個狀態,因爲我已經使用了值顯示/切換一個模式。所以我使用如下。希望它能幫助別人。

class Child extends React.Component { 
    state = { 
    visible:false 
    }; 

    handleCancel = (e) => { 
     e.preventDefault(); 
     this.setState({ visible: false }); 
    }; 

    componentDidMount() { 
    this.props.onRef(this) 
    } 

    componentWillUnmount() { 
    this.props.onRef(undefined) 
    } 

    method() { 
    this.setState({ visible: true }); 
    } 

    render() { 
    return (<Modal title="My title?" visible={this.state.visible} onCancel={this.handleCancel}> 
     {"Content"} 
    </Modal>) 
    } 
} 

class Parent extends React.Component { 
    onClick =() => { 
    this.child.method() // do stuff 
    } 
    render() { 
    return (
     <div> 
     <Child onRef={ref => (this.child = ref)} /> 
     <button onClick={this.onClick}>Child.method()</button> 
     </div> 
    ); 
    } 
} 

參考 - https://github.com/kriasoft/react-starter-kit/issues/909#issuecomment-252969542

相關問題