gpt4 book ai didi

javascript - 如何让 React 组件在每次状态改变时调用一个函数?

转载 作者:行者123 更新时间:2023-12-03 01:25:21 24 4
gpt4 key购买 nike

使用此组件,每次更新时都会像往常一样调用 getDisplay(因此当单击时会隐藏):

class Example extends React.Component {
constructor(props) {
super(props);
this.state = { show: true }
}
getDisplay = () => this.state.show ? 'block' : 'none';
getStyle = () => { { display: this.getDisplay() } }
render = () => <div style={{ display: this.getDisplay() }} onClick={() => { console.log('clicked'); this.setState({ show: false }) }}>
<p>TEST</p>
</div >
}

问题出在这里:当我将渲染元素移动到数组,然后在渲染函数中返回该数组时,它可以工作,但是仅在初始化数组时才会调用 getDisplay 函数,并且不会每次都调用,因此在这种情况下,单击不会不要隐藏

class Example extends React.Component {
array = []
constructor(props) {
super(props);
this.state = { show: true }
//getDisplay is called here instead of getting called on every render/state change.
this.array.push(
<div style={{ display: this.getDisplay() }} onClick={() => { console.log('clicked'); this.setState({ show: false }) }}>
<p>TEST</p>
</div >
)
}
getDisplay = () => this.state.show ? 'block' : 'none';
getStyle = () => { { display: this.getDisplay() } }
render = () => this.array
}

这是我正在开发的应用程序的一个最小示例,我需要将保存 html 元素的数组分开,并使渲染函数返回它。如何使 getDisplay 在第二个代码示例中的每次状态更改时被调用?我希望我解释正确,_,

最佳答案

问题是 this.array 是静态的。在构建时,您正在构建阵列,并且永远不会重新访问它。不要在构造函数中构建 JSX,而是用数据填充数组,然后在渲染时映射它。

render: () => this.array.map(item => (
/* JSX for each item goes here. */
))

请注意,b/c this.array 不是状态,向其中添加新项目不会自动更新它。如果您想要这种行为,请确保 a) 将其存储为状态(例如 this.state = { show: true, array: [] })和 b) 不要改变它(即不要改变它)不要使用 .push,使用 .concat)。

关于javascript - 如何让 React 组件在每次状态改变时调用一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51576187/

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