import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
data: 'First Comes First Serves'
}
this.updateState = this.updateState.bind( this );
};
updateState( e ) {
console.log( e );
// console.log( e.target );
this.setState( {data: e} );
}
render() {
return (
<div>
<Content myDataProp = { this.state.data } updateStateProp = { this.updateState }></Content>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<input type="text" value={ this.props.myDataProp } id="id" />
<div>
<button onClick={ this.props.updateStateProp( document.getElementById( 'id' ).value )}>Click</button>
</div>
<h3>{ this.props.myDataProp }</h3>
</div>
);
}
}
export default App;
错误; 未捕获的类型错误:无法读取 null 的属性“值”
我对 React 还很陌生。
这里,输入值被分配为“先来..”(我想是这样),但出现错误,
提前致谢。
最佳答案
当您使用 React 时,通常最好完全忘记直接在 DOM 上工作的操作,例如 getElementById
。它们要么根本不起作用,要么以意想不到的方式起作用。
相反,看看优秀的 React forms documentation .
在 React 中处理表单的惯用方法是实现 input
的 onChange
事件处理程序,并将当前值存储在组件的状态中。然后您就可以使用它访问并在用户按下按钮时使用它。
关于javascript - React 空值 DOM 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41966633/