|
有两种方式可以解决这个问题
先来介绍第一种方式,使用React.createRef() API 在构造函数里面使用React.createRef() constructor() {
super();
this.author=React.createRef()
}在需要使用refs的标签上绑定:<p classname="emails"><span>email:</span> <input ref="{this.author}" type="text"></p>在方法中获取值//获取当前DOM节点 let author=this.author.current //获取当前DOM节点的值 let author=this.author.current.value 第二种是回调 Refs,React 将在组件挂载时,会调用 ref 回调函数并传入 DOM 元素,当卸载时调用它并传入 null。在 componentDidMount 或 componentDidUpdate 触发前,React 会保证 refs 一定是最新的。 在构造函数里面使用ref的回调函数 constructor() {
super();
this.message=null;
this.setMessage=element=>{
this.message=element;
}
}在需要使用refs的标签上绑定: <textarea ref="{this.setMessage}" name="txtMessage" id="textMessage"></textarea>在方法中获取值: //返回的本来就是DOM节点,所以直接获取节点 let message = this.message; //通过value获取值 let message = this.message.value; |
|