我在一个函数中有一个带有状态和 setState 的父组件,然后将状态和函数传递给子组件以获取值(输入字段在子组件中)。因此,当在子组件中调用该函数时,父组件会更新状态。 function : 该函数在子组件中调用时获得四个参数,即设置状态的值。
父母:
export interface IState {
people: {
name: string,
age: number,
description:string,
note ?: string
}[]
}
class App extends React.Component<IState["people"]> {
state = [
{
name : "",
age : 0,
description: "",
note: ""
}
]
handleState = (name: string,age : number,description : string,note ?: string) => {
this.setState({
name: name,
age: age,
description : description,
note : note
})
}
render(){
return (
<div>
<h1> List of People </h1>
<List people={this.state} />
<AddToList people={this.state} handleState={this.handleState}/>
</div>
);
}
}
孩子:
class AddToList extends React.Component {
state = {
name : "",
description : "",
age: "",
note:""
}
render(){
const handleChange = (e : React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
this.setState({
...this.state,
[e.target.name] : [e.target.value]
})
}
const handleClick = () => {
if(!this.state.name || !this.state.description || !this.state.age ){
return
}
this.props.handleState()
}
return (
<div className="AddToList">
<input type="text" placeholder="name" value={this.state.name} onChange={handleChange} name={"name"}/>
<input type="text" placeholder="description" value={this.state.description} onChange={handleChange} name={"description"}/>
<input type="text" placeholder="age" value={this.state.age} onChange={handleChange} name={"age"}/>
<textarea placeholder="note" value={this.state.note} onChange={handleChange} name="note"/>
<button onClick ={handleClick}>Add</button>
</div>
)
}
}
错误:
Property 'handleState' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
答案 0 :(得分:1)
基本上,您为获得任何道具的组件创建接口。在 App 组件中你什么也没有,那你为什么要在那里添加它呢?
您将 handleState
函数传递给 AddToList
组件,因此您应该在那里添加带有所有值的接口:
interface AddToListProps {
handleState: (name: string,age : number,description : string,note ?:string) => void
}
然后将其添加到 AddToList
。
答案 1 :(得分:1)
您需要在 handleState
组件中为 props AddToList
添加类型
class AddToList extends React.Component <{handleState: (name: string,age : number,description : string,note ?: string) => void}> {}