2017-02-14 79 views
1

我是React新手,我有一個關於從一個組件到另一個組件共享屬性的問題。例如,我想要一個具有「可見」功能的父組件,可以將其傳遞給其他子組件。如何與React組件共享屬性?

例子:

CustomInput visible="true"; 
CustomDropDown visible="false" 

我想知道要做到這一點的最好辦法,尊重的良好做法。感謝您的幫助!

+0

我不太清楚你的意思。你想要傳遞一個'值'或'函數'給子組件嗎?如果它是一個函數,那麼你只是像傳遞它 Jayce444

+0

ChildComponent是我想要的。謝謝您的幫助! –

回答

1

真的很簡單。您可以將方法作爲道具傳遞。假設你有父母,或高階組件(HOC),你可以做這樣的事情:

class Parent extends React.Component { 
    logWord = (word) => { 
    console.log(word); 
    } 

    render() { 
    return <ChildComponent handleLogging={ this.logWord } /> 
    } 
} 

然後,在ChildComponent,你只需從道具訪問方法。例如:

class ChildComponent extends React.Component { 
    render() { 
    return (
     <div onClick={ this.props.handleLog.bind(null, 'Logged!') }>Click me to log a word!</div> 
    } 
    } 
} 

所以,在你的例子,如果你想要的是上更新您的狀態的可見性屬性父存在的方法,你可以寫:

class Parent extends React.Component { 
    constructor() { 
     this.state = { 
      visible: false 
     } 
    } 

    setVisible = (bool) => { 
     this.setState({ visible: bool }); 
    } 

    render() { 
     return <ChildComponent updateVisible={ this.setVisible } visible={ this.state.visible } />; 
    } 
} 

ChildComponent:

class ChildComponent extends React.Component { 
    render() { 
    return (
     <div> 
     <div onClick={ this.props.updateVisible.bind(null, true) }>Set me to visible!</div> 
     <div onClick={ this.props.updateVisible.bind(null, false) }>Set me to invisible!</div> 
      { this.props.visible && <div>I'm visible right now!</div> } 
     </div> 
    } 
    } 
} 
+0

非常感謝monners,這幫了我很多! –

+0

沒問題。歡迎來到React的精彩世界! – monners