React element 处理事件跟使用 DOM element 处理事件差异:
<element onclick="myScript[String]"> \\React DOM
<element onClick="myScript[Function]"> \\HTML DOM
Class Component 或 function component 稍微有不同的写法,但差不多是
以下完整例子
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 为了让 `this` 能在 callback 中被使用,这里的绑定是必要的:
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'} </button>
);
}}
ReactDOM.render(
<Toggle />, document.getElementById('root'));
const { useState } = React;
function Toggle() {
const [state, setState] = useState(true);
function handleClick(e) {
e.preventDefault();
setState(!state)
}
return (
<button onClick={handleClick}>
{state ? 'ON' : 'OFF'}
</button>
);
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
class Toggle extends React.Component {
//略
handleClick(id) {
console.log(id) //#a5aa
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick.bind(this, '#a5aa')}>
{this.state.isToggleOn ? 'ON' : 'OFF'} </button>
);
}}
//略
除了使用 bind 也可以写成 arrow function ,而下一篇会继续介绍为什麽要使用 bind 。
button onClick={() => this.deleteRow('id')}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, 'id')}>Delete Row</button>
以上今天
参考资料:
https://zh-hant.reactjs.org/docs/handling-events.html
理解 JS 里面的 bind
根据 Google 的官方消息指出在 2021 年的六月有对 SEO 的演算法稍作调整。会特别将网页...
物件导向的设计中,关於建构物件的方式我们成为建构器(constructor),这关系到物件使用的方式...
一个月的光阴已过去 经过一个月的考试筛选 我们遗憾离开一位同学 但在此时 也展开游戏专题的序幕 我选...
毒液2线上 《毒液2》(英语:Venom: Let There Be Carnage,香港译《毒魔:...
1.Refs 似 Document.getElementById() (1)直操作DOM <i...