我实际上是 React 的新手,在学习 Lifting State Up 的教程时,我在尝试修改 Child.js 的值时遇到了问题。它拒绝未定义的错误。第二个问题 为什么当属性为value而不是defaultValue时无法修改Input值?
提前致谢。
Parent.js
import React,{Component} from 'react';
import Child from './child';
export default class Parent extends Component{
constructor(props){
super(props);
this.change= this.change.bind(this)
this.state={
num:0
}
}
onChangeValuebyChild(event){
/* this.setState({
num: document.getElementById('haha').value
})*/
this.setState({
num: parseFloat(event.target.value)
})
}
change(event){
this.setState({
num: event.target.value
})
}
render(){
const val= parseFloat(this.state.num)
return (<div>
<input defaultValue={val} onChange={(event)=>this.change(event)}/>
{val}
<Child numero={val} onChangeByParent={(e)=>this.change(e)}/>
<Child numero={val} onChangeByParent={this.change}/>
</div>)
}
}
Child.js
import React, {Component} from 'react';
export default class Child extends Component{
constructor(props){
super(props)
this.onHandlee=this.onHandle.bind(this)
this.input=React.createRef()
}
onHandle(e){
this.props.onChangeByParent(e.target.value)
}
render(){
const val = parseFloat(this.props.numero);
return(<div>
<input
id='haha' ref={this.input}
defaultValue={val}
onChange={(e)=> this.onHandle(e)}
/> {val}
</div>)
}
}
最佳答案
在这个 fiddle 中解决了您的问题:https://jsfiddle.net/crystalthinker/c43hwdtj/
- 你在 this.onHandlee=this.onHandle.bind(this) 的构造函数中有错别字;应该是 this.onHandle=this.onHandle.bind(this);
你犯的错误是你的 parent :
change(event){
this.setState({
num: event.target.value
})
}
这会接受一个事件,并且您正在传递一个来自 child 的值。
onHandle(e){
this.props.onChangeByParent(e.target.value)
}
将此更改为
onHandle(e){
this.props.onChangeByParent(e)
}
- 当您为输入属性赋值时,就像说出输入元素的当前值。如果您正在使用,请使用状态进行更改:
示例:
<input type="text" value={this.state.inputVal} onChange={(e) => {this.setState({inputVal: e.target.value})}} />
, 当您使用 defaultValue 时,它是分配给输入的初始值。
关于javascript - 子组件中的事件返回未定义的 ' Uncaught TypeError: Cannot read property ' 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51946063/