我是React Native的新手,我正在尝试创建一个TextInput,我可以根据textInput的焦点状态设置样式 . 我的理解是子类化反应不大,所以我正在尝试创建包含文本输入的组件的方法 .
所以我创建了这个组件:
class FocusTextInput extends React.Component<{}, { isFocused: boolean }> {
constructor(props: {}) {
super(props);
this.state = { isFocused: false };
}
onFocus() {
this.setState({ isFocused: true });
}
onBlur() {
this.setState({ isFocused: false });
}
render() {
return (
<TextInput
{...this.props}
// style={this.state.isFocused ? { backgroundColor: 'red' } : { backgroundColor: 'green' }}
style={{ backgroundColor: '#aaa' }} // <<<<<<<<<<<<<< If i delete this line then it works, just no style override
/>
);
}
}
而我正试图像这样使用它:
<FocusTextInput
ref="digit0"
isFocused="false"
onChangeText={this.handleDigitChanged.bind(this, 0)}
style={styles.digitFramedControlDigit}
maxLength={1}
returnKeyType="next"
selectTextOnFocus
selectionColor="#ffffff00"
/>
所以我能够将这些属性传递给子(TextInput),我怎么能覆盖样式呢?
另外,我不确定这是正确的方法,好像我想在我的FocusTextInput上调用InputText公开的任何hte方法,我必须声明这些方法并转发方法调用 . 这看起来很傻 .
任何帮助赞赏 .
2 回答
您可以尝试添加!对您造型很重要 . 见下文 .
最推荐的方法是使用数组语法来覆盖父级:
在孩子( FocusTextInput ),申请:
style={[{ backgroundColor: '#aaa' }, this.props.style]}
它从左到右阅读 . 所以
backgroundColor
默认为#aaa . 如果this.props.style
有新的定义,那么它将覆盖前一个(s) .