admin管理员组

文章数量:1335170

I'm using React and when a user clicks on the <li> tag, the popup method is fired, but the ponent inside the method is not shown, the popup ponent does not get fired, why is that?

  export default class Main extends React.Component {
  constructor(props) {
    super(props);
  }
  popup(value) {
    console.log('fired ok');
    //call popup ponent
    <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>
    )
  }
}

I'm using React and when a user clicks on the <li> tag, the popup method is fired, but the ponent inside the method is not shown, the popup ponent does not get fired, why is that?

  export default class Main extends React.Component {
  constructor(props) {
    super(props);
  }
  popup(value) {
    console.log('fired ok');
    //call popup ponent
    <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>
    )
  }
}
Share Improve this question edited Jul 10, 2016 at 20:27 Soviut 91.8k53 gold badges208 silver badges282 bronze badges asked Jul 10, 2016 at 20:05 Gilad AdarGilad Adar 1931 gold badge5 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You would need to actually render the Popup element, something along the lines of:

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 on the black "Click Me!" text.

I hope that helps!

本文标签: javascriptreact JS render a component after a clickStack Overflow