更新handleClick React中的组件 [英] Update component within handleClick React
本文介绍了更新handleClick React中的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在更新/更改组件状态时遇到问题.这是我要工作的代码:
I am having problem with updating/changing state of the components. Here is the code which i am trying to make work:
class NavbarList extends React.Component {
constructor() {
super();
this.onClick = this.handleClick.bind(this);
}
handleClick(event) {
const {id} = event.target;
console.log(id);
return <h3 id={1} onClick={this.onClick}>New Text</h3>
}
render() {
return (
<h3 id={0} onClick={this.onClick}>Old Text</h3>
)};
};
ReactDOM.render(
<NavbarList />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
带有条件渲染的示例并没有为我清除它.
Examples with coditional rendering did not cleared it out for me.
我需要更多的珍品.
推荐答案
您可以使用状态保存ID和文本,而不是返回新的JSX元素,然后在单击时更新状态.
Instead of returning a new JSX element, you could use the state to save id and text, then update the state on click.
class NavbarList extends React.Component {
constructor() {
super();
this.state = {
text: "Old Text",
id: 0
};
this.onClick = this.handleClick.bind(this);
}
handleClick(event) {
const {id} = event.target;
console.log(id);
this.setState({
text: "New text",
id: 1
});
}
render() {
return (
<h3 id={this.state.id} onClick={this.onClick}>{this.state.text}</h3>
)};
};
ReactDOM.render(
<NavbarList />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
这篇关于更新handleClick React中的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文