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;
添加回答
舉報