gpt4 book ai didi

javascript - 如何在ReactJS中处理数组对象的onClick事件?

转载 作者:行者123 更新时间:2023-11-28 04:01:49 25 4
gpt4 key购买 nike

我正在尝试向数组中的对象添加一个 onClick 事件处理程序,其中单击的对象的类发生了更改,但它不是仅更改一个元素的类,而是更改了所有元素的类元素。

如何让该函数一次仅对一个 section 元素起作用?

class Tiles extends React.Component {
constructor(props) {
super(props);
this.state = {
clicked: false,
content : []
};
this.onClicked = this.onClicked.bind(this);

componentDidMount() {
let url = '';
let request = new Request(url, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
})
});
fetch(request)
.then(response => response.json())
.then(data => {
this.setState({
content : data
})
} );

}

onClicked() {
this.setState({
clicked: !this.state.clicked
});
}

render() {
let tileClass = 'tile-content';
if (this.state.clicked) {
tileClass = tileClass + ' active'
}
return (
<div className = 'main-content'>
{this.state.pages.map((item) =>
<section key = {item.id} className = {tileClass} onClick = {this.onClicked}>
<h4>{item.description}</h4>
</section>)}
<br />
</div>
)
}

class App extends React.Component {
render() {
return (
<div>
<Tiles />
</div>
)
}
}

ReactDOM.render(
<App />,
document.getElementById('content-app'))

最佳答案

您在“main-content”类中定义了 onClicked() 。这就是它的火点。

constructor(props) {
// super, etc., code
this.onClicked = this.onClicked.bind(this); // Remove this line.
}

删除该部分。

您可以将 onClicked() 函数保留在原来的位置。不过,您在 render() 中的调用不正确:onClick = {this.onClicked}>。它访问 onClicked ATTRIBUTE,而不是 onClicked FUNCTION,它应该是 this.onClicked()。

让我稍微清理一下 render() 中的调用:

render() {
let tileClass = 'tile-content';
return (
<div className = 'main-content'>
// some stuff
<section
key={item.id}
className={tileClass}
onClick={() => this.onClicked()} // Don't call bind here.
>
<h4>{item.description}</h4>
</section>
// some other stuff
</div>
)
}

关于javascript - 如何在ReactJS中处理数组对象的onClick事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47045136/

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