单击后,JS渲染组件

时间:2016-07-10 20:05:43

标签: javascript reactjs

我正在使用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 个答案:

答案 0 :(得分:5)

您需要实际呈现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>
    )
  }
}

Here's a fiddle of it in action。点击黑色“Click Me!”文本。

我希望有所帮助!