我有一个MovieSearch
组件:
render() {
const greeting = 'Welcome to React'
return (
<React.Fragment>
<SearchAPI />
<SearchAPIResults message={greeting}/>
</React.Fragment>
)
}
将字符串道具传递给它的子SearchAPIResults
组件:
// works
function SearchAPIResults(props) {
return (
<h1>{props.message}</h1>
);
}
// does not work
// class SearchAPIResults extends React.Component {
// constructor(props) {
// super(props)
// this.state = {message: props.message}
// }
// }
顶部代码段起作用。如果尝试使用底部代码,则会在MovieSearch
组件中收到一条消息:
输入'{message:string; }'不能分配给'IntrinsicAttributes&IntrinsicClassAttributes&Readonly <{}>&Readonly <{children ?: ReactNode; }>'。属性'message'在类型'IntrinsicAttributes和IntrinsicClassAttributes&Readonly <{}>和Readonly <{子代上不存在:ReactNode; }>'。
我知道Class和Function组件之间是有区别的,并且我认为SearchAPIResults
组件应该是Function组件,因为它仅显示一些数据。但是我仍然想知道如何在两个Class组件之间传递道具。
答案 0 :(得分:4)
好像您正在使用TypeScript。在这种情况下,您必须告诉TS组件prop的结构是什么。否则,它不知道message
道具的类型。如果您使用的是功能组件或类组件,则可以这样做,但是语法会有所不同:
type Props = {
message: string;
};
const SearchAPIResults: React.FC<Props> = (props) {
return (
<h1>{props.message}</h1>
);
}
或
type Props = {
message: string;
};
class SearchAPIResults extends React.Component<Props> {
constructor(props) {
super(props)
this.state = {message: props.message}
}
render() {
return (
<h1>{this.state.message}</h1>
);
}
}
编辑:作为旁注,这样做:
this.state = {message: props.message}
通常是React中的反模式,您应该避免使用它。不要使用道具来设置组件的状态-这样做会在应用程序中的数据的“真相来源”产生冲突和混乱。如果message
属性发生变化,则由于state
中存储的值已过时,您的子组件将无法正确更新。只需直接阅读message
道具,不要将其存储在状态中即可。
class SearchAPIResults extends React.Component<Props> {
render() {
return (
<h1>{this.props.message}</h1>
);
}
}