【问题标题】:When to use this.prop when passing down props?传递 props 时何时使用 this.prop?
【发布时间】:2020-05-30 17:33:58
【问题描述】:
我是 JS/React 的初学者,我正试图围绕何时使用 this.prop 或仅在 React 中不使用 this 传递 props 的概念。
在某些来源中,编码器总是使用 this.prop,而在其他来源中,这似乎是不必要的。谁能解释一下?
在本例中,我们将 props 用户名、authed、logout 和 header 从应用程序传递给 hello。为此,我们使用 this.props。每次我们导入。
然而,在这个例子(React Native)中,我们将 term、onTermChange 和 onTermSubmit 从 searchscreen 传递到 searchbar,而不使用 this.props。然后我相信我们在搜索栏的 TextInput 中重新定义了我们的道具,因此它的 onEndEditing 与搜索屏幕中的 onTermSubmit 相同。
我认为 this.props 可能是一种反应语法,它在 React Native 中得到了简化。但是,我在 React 中遇到了另一个不使用 this.props 的示例:
【问题讨论】:
标签:
javascript
reactjs
react-native
【解决方案1】:
当你有一个类组件时,你将使用“this”。当你有一个功能组件时,就不需要了,因为你没有创建一个类的实例。传递给类的所有参数都存储在“this.props”中。
因此,在您的第二个示例和第三个示例中,您有功能组件,它们将传递给它们的 const 不是作为道具,而是作为具有自己名称的实际常量。
希望这会有所帮助。
【解决方案2】:
props 在这两种情况下都被使用。您只是以不同的方式访问道具值。第一个示例使用 Class 组件。这意味着props 作为this.props 传递给子级,其中第二个示例使用无状态/函数式组件,这意味着没有this。和
const FunctionalComponent = (props) => {
const {name, onLogin} = props
......
}
等价于
const FunctionalComponent = ({name, onLogin}) => {
.....
}
由于对象解构,因此在第二个示例中您没有看到props 的显式使用。
【解决方案3】:
这不是React 的东西,而是JavaScript 的东西。
类 - 在这里您需要使用 this 关键字访问 state 和 props。
函数 - 这里你不需要在 React 中使用 this。这里函数组件的参数是props,所以你可以直接使用props.something而不是this.props.something。
在您的搜索栏组件中:-
const Searchbar = ({term,onTermSubmit,onTermChange}) 表示属性
term、onTermSubmit 和 onTermChange 正在从 props 对象中解构,因此现在可以直接使用。您不再需要像 props.term 那样访问它们。它们可以直接访问,如term,无论您希望它们在哪里。