这次给大家带来React中组件事件使用详解,React中组件事件使用的注意事项有哪些,下面就是实战案例,一起来看一下。
事件可以直接写到 DOM 节点,然后通过 ref 来获取 DOM 节点
import React from 'react';
import ReactDOM from 'react-dom';
class Component1 extends React.Component{
focusHandler(){
this.refs.name.focus();
}
render(){
return (
<p>
<input type="text" name="name" placeholder="" ref="name"/>
<input type="button" name="" value="focus" onClick={this.focusHandler} />
</p>
);
}
};
ReactDOM.render(<Component1/>, document.getElementById('p1'));效果预览
React 在事件方法调用上默认会传一个形参events,该对象是一个合成事件,所以不需要担心浏览器兼容的问题。
import React from 'react';
import ReactDOM from 'react-dom';
class Component1 extends React.Component{
submit(e){
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit" onClick={this.submit}/>
}
}
ReactDOM.render(
<Component1 />,
document.getElementById('app')
)在所有的事件当中,首先都要弄明白 this 指向哪里。而 React 事件中(如上面的案例)默认的 this 都是 undefined,为了 this 指针能正确指回组件对象本身,通常可以用下面几种方法。
class Component1 extends React.Component{
submit = (e) => {
console.log(this)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit" onClick={this.submit}/>
}
}class Component1 extends React.Component{
submit(e){
console.log(this)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit" onClick={(e) => this.submit(e)}/>
}
}class Component1 extends React.Component{
constructor(props){
super(props)
this.submit = this.submit.bind(this);
}
submit(e){
console.log(this)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit" onClick={this.submit}/>
}
}class Component1 extends React.Component{
submit(e){
console.log(this)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit" onClick={this.submit.bind(this)}/>
}
}class Component1 extends React.Component{
submit(e, n){
console.log(this, n)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit" onClick={(e) => this.submit(e, 100)}/>
}
} submit(n, e){
console.log(n)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit" onClick={this.submit.bind(this, 20)}/>
}
}相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
以上就是React中组件事件使用详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号