我在纯react中创建了这个类,我想将它转换为react钩子。我开始起步,但没有如预期的那样。以下是代码:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { name: 'Frarthur' };
this.changeName = this.changeName.bind(this);
}
changeName(newName) {
this.setState({
name: newName
});
}
render() {
return <Child name={this.state.name} onChange={this.changeName} />
}
}
);
我想在react hook中做这个例子。
function Parent () {
const [changeName] = React.useState(name);
const handleIncrement = () => setChange(newName);
return (
<div>
<div>
<div>{name}</div>
<Parent name={this.state.name} onChange={this.changeName} />
</div>
</div>
);
}
挂钩模拟Parent
类组件:
const Parent = () => {
const [name, changeName] = React.useState('Frarthur');
return <Child name={name} onChange={changeName} />;
};
如果您的需求不理想,您希望将其转换为功能组件不HOOK
const Parent = (props) => {
const [name, setName] = React.useState("Frathur");
const changeName = (newName) => {
setName(newName);
}
return <Child name={name} onChange={changeName} />
}