如何将 React hook 的 setter 发送到另一个组件
How to send React hook's setter to another component
我有这种钩子:-
const [profile, setProfile] = useState({
displayName: '',
realName: '',
birthDate: '',
height: 0,
cityLocation: '',
occupation: '',
ethnicity: ''
}
稍后在代码中,我将它作为道具传递给 class 组件:-
<SelectEthnicity
data={{profile:profile,
setProfile: {setProfile}}}
/>
SelectEthnicity 是一个 class 组件。它只是 select 的包装器。这个 select 有很多选择。这是小代码片段。
export class SelectEthnicity extends Component {
render() {
console.warn("this.props.data.setProfile", this.props.data.setProfile)
return (
<select value={this.props.data.profile.ethnicity} // this is fine.
// TypeError: this.props.data.setProfile is not a function
onChange={(input) => {this.props.data.setProfile({ ...this.props.data.profile, [input.target.name]: input.target.value })}}
name="ethnicity" ref={this.props.form.register}>
<option value="">Select...</option>
<option value="white">White</option>
<option value="southAsian">South Asian</option>
<option value="southEastAsian">South East Asian</option>
<option value="mixed">Mixed</option>
我得到一个错误:
TypeError: this.props.data.setProfile is not a function
所以 porps 没有将 setProfile 作为函数传递。我该怎么做?
在您的示例中,setProfile 是一个包含 setProfile 函数的对象。
你只需要去掉它周围的花括号。
<SelectEthnicity
data={{
profile: profile,
setProfile: setProfile
}}
/>
或者:
<SelectEthnicity data={{ profile, setProfile }} />
我有这种钩子:-
const [profile, setProfile] = useState({
displayName: '',
realName: '',
birthDate: '',
height: 0,
cityLocation: '',
occupation: '',
ethnicity: ''
}
稍后在代码中,我将它作为道具传递给 class 组件:-
<SelectEthnicity
data={{profile:profile,
setProfile: {setProfile}}}
/>
SelectEthnicity 是一个 class 组件。它只是 select 的包装器。这个 select 有很多选择。这是小代码片段。
export class SelectEthnicity extends Component {
render() {
console.warn("this.props.data.setProfile", this.props.data.setProfile)
return (
<select value={this.props.data.profile.ethnicity} // this is fine.
// TypeError: this.props.data.setProfile is not a function
onChange={(input) => {this.props.data.setProfile({ ...this.props.data.profile, [input.target.name]: input.target.value })}}
name="ethnicity" ref={this.props.form.register}>
<option value="">Select...</option>
<option value="white">White</option>
<option value="southAsian">South Asian</option>
<option value="southEastAsian">South East Asian</option>
<option value="mixed">Mixed</option>
我得到一个错误:
TypeError: this.props.data.setProfile is not a function
所以 porps 没有将 setProfile 作为函数传递。我该怎么做?
在您的示例中,setProfile 是一个包含 setProfile 函数的对象。
你只需要去掉它周围的花括号。
<SelectEthnicity
data={{
profile: profile,
setProfile: setProfile
}}
/>
或者:
<SelectEthnicity data={{ profile, setProfile }} />