2017-01-23 59 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} />}

相关问题