[英]React.createRef is not a function in react-rails
我在ruby on rails项目中使用react-rails gem。 我尝试添加对DOM元素的引用。 这是我的组成部分:
class NewItem extends React.Component {
constructor(props) {
super(props);
this.name = React.createRef();
}
handleClick() {
var name = this.name.value;
console.log(name);
}
render() {
return (
<div>
<input ref={this.name} placeholder='Enter the name of the item' />
<button onClick={this.handleClick}>Submit</button>
</div>
);
}
};
当我尝试在浏览器中加载页面时,我在控制台中有此消息: TypeError: React.createRef is not a function. (In 'React.createRef()', 'React.createRef' is undefined)
TypeError: React.createRef is not a function. (In 'React.createRef()', 'React.createRef' is undefined)
。
更新响应16.3 React.createRef()这个API被添加到react 16.3 checkout这个https://github.com/facebook/react/pull/12162
尝试改变这个
handleClick() {
var name = this.name.value;
console.log(name);
}
至
handleClick = () => {
var name = this.name.current.value;
console.log(name);
}
不要使用ref来获取输入值。 使用此方法
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.