gpt4 book ai didi

javascript - react JS 在点击后渲染一个组件

转载 作者:行者123 更新时间:2023-11-29 16:48:34 26 4
gpt4 key购买 nike

我正在使用 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>
)
}
}

最佳答案

您需要实际呈现 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 .点击黑色的“点击我!”文本。

希望对您有所帮助!

关于javascript - react JS 在点击后渲染一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38296018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com