react引入插件进行跨组件通信,安装依赖包 npm i events
import { EventEmitter } from 'events'
const eventBus = new EventEmitter()
eventBus.addListener(事件名,回调函数)
removeListener(事件名,回调函数)
emit(事件名,参数)
受控组件和非受控组件
- 受控组件使用 change input 事件 evnet.target.value 减少ref的使用
class Demo extends React.Component {
state = {
username: '',
password: ''
}
render() {
return (
<div>
<input onChange={this.handleRef} name="username" type="text" />
<br />
<input onChange={this.handleRef} name="password" type="password" />
</div>
)
}
handleRef = (event) => {
this.setState({ [event.target.name]: event.target.value })
}
}
- 非受控组件使用 ref来获取元素
class Demo extends React.Component {
myRef = React.createRef()
render() {
return (
<div>
<input ref="input1" onChange={this.handleChange} type="text" />
<input ref={c => this.input2 = c} onChange={this.handleRef} type="text" />
<input ref={this.myRef} onChange={this.handleRef} type="text" />
</div>
)
}
handleRef = (event) => {
console.log(this.refs.input1);
console.log(this.input2);
console.log(this.refs);
console.log(event.target.value);
console.log(this.myRef.current.value);
this.myRef.current.focus()
}
}
|