我有一个 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
组件中收到一条消息:
Type '{ message: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. Property 'message' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
我知道类和函数组件之间存在差异,并且我认为 SearchAPIResults
组件应该是函数组件,因为它只显示一些数据。但我仍然想知道如何在 2 个类组件之间传递 props。
最佳答案
看起来您正在使用 TypeScript。在这种情况下,你必须告诉 TS 你的组件 props 的结构是什么。否则它不知道 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 中的反模式,你应该避免它。不要使用 props 来设置组件的状态 - 这样做会造成应用程序中数据的“真相来源”的冲突和困惑。如果 message
属性发生更改,您的子组件将无法正确更新,因为存储在 state
中的值已过时。只需直接读取 message
属性,不要将其存储在状态中。
class SearchAPIResults extends React.Component<Props> {
render() {
return (
<h1>{this.props.message}</h1>
);
}
}
关于reactjs - React ES6 和传递 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63131107/