2017-01-23 60 views
-1

我有一個問題..如何將狀態發送到條件組件?

請幫助我。

我的工作反應JS

如何發送的狀態條件發生反應成分?

this.state = { 
isTrue: false, 
name: undefined 
} 

handleClick(e){ 
this.setState({ 
    isTrue: true, 
    name: 'adwin' 
}) 
} 

//////// render return /////// 

{this.state.isTrue ? (
    <App2 name={this.state.name} /> 
) : '' 
} 



////// in App2 component ////// 
componentDidMount(){ 
console.log(this.props.name) //>>> it work undefined 
} 
+0

這不是在所有清楚你在問什麼。請使用Stack Snippets('[<>]'工具欄按鈕)使用** runnable ** [mcve]更新您的問題。 Stack Snippets支持React,包括JSX; [這是如何做一個](http://meta.stackoverflow.com/questions/338537/)。 –

回答

1

您將prop傳遞給子組件的方式是正確的。你可以嘗試通過props作爲參數的子組件的構造類似

class App extends React.Component { 
 
    constructor() { 
 
    super(); 
 
    this.state = { 
 
    isTrue: false, 
 
    name: undefined 
 
    } 
 
    } 
 
    
 

 
    handleClick = (e) => { 
 
    this.setState({ 
 
    isTrue: true, 
 
    name: 'adwin' 
 
    }) 
 
    } 
 
    render() { 
 
    return (
 
     <div> 
 
     {this.state.isTrue ? (
 
      <App2 name={this.state.name} /> 
 
     ) : '' 
 
     } 
 
     <button onClick={this.handleClick}>Click</button> 
 
     </div> 
 
    ) 
 
    } 
 
} 
 
class App2 extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    } 
 
    componentDidMount(){ 
 
    console.log(this.props.name) 
 
    } 
 
    render() { 
 
    return (
 
     <div> 
 
     {this.props.name} 
 
     </div> 
 
    ) 
 
    } 
 

 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script> 
 
<div id="app"></div>

1

,如果你只是想找一個條件,你可以做{this.state.isTrue && <App2 name={this.state.name} />}

相關問題