reactjs - React ES6 和传递 props

标签 reactjs typescript ecmascript-6

我有一个 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/

相关文章:

javascript - 闭包编译器无法编译保留字 "default"

reactjs - 如何在react js中的图像onload事件回调中使用函数?

node.js - 在 React 中使用 Apollo.js 将查询映射到 props

javascript - 在 TypeScript 中命名抽象类和接口(interface)

typescript - 创建一个实现具有重载函数的接口(interface)的匿名对象

javascript - Webpack/ES6 动态导入

reactjs - 如何在reactjs中使用material-ui以红色显示helperText

reactjs - 如何在每次用户打开屏幕时获取数据并仅在获取的数据与状态中的当前数据不同时才更新状态

javascript - 找不到模块的声明文件

javascript - 如何使用类和函数为 html5-canvas 上的多个对象设置动画?