2 回答
TA贡献1818条经验 获得超11个赞
您的两个组件看起来都有问题,需要进行许多更正
你的代码
//don’t what is Connect here. A class followed its class name must be single word
class Main Connect extends Component {
constructor(props) {
//you need to call super(props); here to get props from parent inside constructor
// set age to a state but what you are doing below isn’t right way
this.age = this.props.age
}
render() {
// this is totally wrong check my corrected code below to understand better
<Child />
return(this.age)
}
}
class Child Connect extends Component {
render()
return(<Main age='21' />)
}
检查以下更新的代码。这是从父到子的工作方式
class Main extends Component{
render() {
return (<div><Child age='21' /></div>)
}
}
class Child extends Component {
constructor(props){
super(props);
this.state = {
age: props.age
}
}
render(){
return(<div><h1>{this.state.age}</h1></div>)
}
PS:- 你得到了其他人的反对票,因为句子不正确,而且你发布的内容不完整,有很多问题。
TA贡献1820条经验 获得超9个赞
我不确定你的情况是什么。输入元素的变化是向上传递 props 的典型情况。为此,通过属性使用函数来处理更改(并将实际值传递回输入):
主程序
import AgeInput from './AgeInput';
class Main extends Component {
state = {
age: ''
}
handleAgeInputChange = ({target}) => {
const { value: age } = target;
this.setState({ age })
}
render() {
return <AgeInput onChange={this.handleAgeInputChange} value={this.state.age} />
}
}
AgeInput.js(儿童)
const AgeInput = ({ onChange, value }) => (
<input onChange={onChange} value={value} />
);
export default AgeInput;
添加回答
举报