如何在功能组件中使用 {...this.props}
2020-03-04
840
我在 Udemy 上购买了 React-Native 课程,教授 React-Native 的人使用了
{...this.props
。
但对我来说没用。这是错误消息。
TypeError: undefined is not an object(evaluating '_this.props')
我该怎么办?
LoginForm.js
import React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import Input from '../components/Input';
const LoginForm: () => React$Node = () => {
return (
<>
<View>
<Text style={styles.signInText}>SIGN IN</Text>
<Input
placeholder="Username"
/>
</View>
</>
);
};
const styles = StyleSheet.create({
signInText:{
fontWeight:'bold',
marginVertical:25,
color:'#189BDD'
}
});
export default LoginForm;
Input.js
import React from 'react';
import { StyleSheet, ScrollView, View, TextInput, Image } from 'react-native';
const Input: () => React$Node = () => {
return (
<>
<View>
<TextInput
{...this.props}
/>
</View>
</>
);
};
const styles = StyleSheet.create({});
export default Input;
Udemy 教师 SS
2个回答
this
不会存在于函数式组件中。在函数式组件中,您将 props 作为参数访问,但您并未传递该参数。
const Input = (props) => {
...
<TextInput
{...props}
/>
}
Brian Thompson
2020-03-04
创建 React 组件有两种方式:类或函数。
此处的输入
是函数组件,而不是类组件。
这意味着
props
是作为参数传递给函数的,而不是作为类实例的属性。
this
不用于函数组件,只用于类组件。
因此,像这样声明您的函数组件:
const Input = (props) => {
然后像这样传播 props:
{...props}
Alex Wayne
2020-03-04