在我的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)。
发布于 2018-06-07 21:36:51
将react更新到16.3 React.createRef()此接口是在react 16.3中添加的。签出此https://github.com/facebook/react/pull/12162
发布于 2018-05-02 03:41:01
尝试更改此设置
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>
);
}
}https://stackoverflow.com/questions/50122421
复制相似问题