我在下面有一个样式化的类组件,它定义了一个TextInput以及带有Icon和占位符的两个道具。
import React, { Component } from "react";
import { View, Text, TextInput } from "react-native";
import styled from "styled-components/native";
const StyledView = styled.View`
...
`;
const StyledIconView = styled.View`
...
`;
const StyledTextInput = styled.TextInput`
...
`;
class LoginTextInput extends React.Component {
constructor(props) {
super(props);
this.state = { text: this.props.text };
}
render() {
const { Icon } = this.props; // it seems have a problem here
return (
<StyledView>
<StyledIconView>
<Icon /> // and here
</StyledIconView>
<StyledTextInput
placeholder={this.state.text}
onChangeText={searchString => {
this.setState({ searchString });
}}
/>
</StyledView>
);
}
}
export default LoginTextInput;
然后我可以使用此组件自定义我自己的案例。
import React from "react";
import { View, Text, StyleSheet, TextInput } from "react-native";
import LoginTextInput from "./LoginTextInput";
import Icon from "react-native-vector-icons/FontAwesome";
import SimpleIcon from "react-native-vector-icons/SimpleLineIcons";
const UserIcon = () => <Icon name="user-o" size={20} color="#757575" />;
class Login extends React.Component {
constructor(props) {
super(props);
this.state = { text: "Useless Placeholder" };
}
render() {
return (
<View>
/* <LoginTextInput text="input use name" Icon={UserIcon} /> */
<LoginTextInput text="input use name" Icon={<UserIcon />} />
</View>
);
}
}
export default Login;
但是该代码无法编译并报告"expect a string or a class/function, but get: undefined"
错误。
我标记了上面的错误,看来Icon
道具无法在此代码中定义。
解决方案
由于我使用了UserIcon组件,因此应将其更改为<UserIcon / >
。