开发者问题收集

React JS 在点击后渲染组件

2016-07-10
8330

我正在使用 React,当用户点击 <li> 标签时,会触发弹出方法,但方法内的组件不会显示,弹出组件不会触发,这是为什么?

  export default class Main extends React.Component {
  constructor(props) {
    super(props);
  }
  popup(value) {
    console.log('fired ok');
    //call popup component
    <Popup value={value} />
  }
  render() {
    return (
      <ul>
        <li key={0} onClick={() => this.popup(value)} />
      </ul>
    )
  }
}

export default class Popup extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    console.log('this is not fired');
    const { value } = this.props;

    return (
      <div class="popup">
        <p>{value}</p>
      </div>
    )
  }
}
1个回答

您实际上需要渲染 Popup 元素,类似于以下内容:

export default class Main extends React.Component {
  constructor(props) {
    super(props);
    // save the popup state
    this.state = {
        visible: false, // initially set it to be hidden
        value: '' // and its content to be empty
    };
  }
  popup(value) {
    console.log('fired ok');
    this.setState({
      visible: true, // set it to be visible
      value: value // and its content to be the value
    })
  }
  render() {
    // conditionally render the popup element based on current state
    const popup = (this.state.visible ? <Popup value={this.state.value} /> : null);
    return (
      <ul>
        {popup} 
        <li key={0} onClick={() => this.popup('Hello World')}>Click Me!</li>
      </ul>
    )
  }
}

这是实际操作 。单击黑色的“点击我!”文本。

希望对您有所帮助!

m-a-r-c-e-l-i-n-o
2016-07-10