通过自定义组件将带有“ this”的prop函数传递给子组件

时间:2019-01-11 18:58:54

标签: react-native

我正在尝试创建自定义TextInput-我不想直接扩展TextInput类,因为将来可能会与其他库一起使用。但是我确实想将onChangeText函数从脚本的顶层传递到自定义组件,再传递给子TextInput

在下面的脚本中,我为自定义组件提供了一个默认的onChangeText函数,我想将该函数传递给TextInput。显然,在这种情况下,“ this” setState不像我希望的那样引用TextInput。这是指我的自定义组件。

即使我能弄清楚如何获得默认的onChangeText来引用TextInput对象的setState,当我实际使用MyTextInput onChangeText =(text时,也将如何引用它。 )=> ????呢?

export class MyTextInput extends React.Component {
    static propTypes = {
        placeholder: PropTypes.string,
        style: PropTypes.object,
        onChangeText: PropTypes.func,
        password: PropTypes.bool,
    }

    static defaultProps = {
        password: false,
        onChangeText: (text) => this.setState({text}),
    }



    render() {

        return (
            <TextInput
                style={[styles.textinput, this.props.styles]}
                placeholder={this.props.placeholder}
                placeholderTextColor={colors.text}
                secureTextEntry={this.props.password}
                onChangeText={this.props.onChangeText}
              />
        );
    }
}

您显然会看到defaultProps中的onChangeText包含一个“ this”,当该函数引用TextInput时引用了我的组件

你们认为最好的方式是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

解决方案

您想扩展onChangeText以使用父组件而不更改原始行为。 因此,onChangeText属性的链接方法如下。

export class MyTextInput extends React.Component {
    state = {
      value: '',
    }
    
    static propTypes = {
        placeholder: PropTypes.string,
        style: PropTypes.object,
        onChangeText: PropTypes.func,
        password: PropTypes.bool,
    }

    static defaultProps = {
        password: false,
    }
    
    onChangeText = (value) => {
      this.setState({ value });
      this.props.onChangeText?.(); // Same as this.props.onChangeText && this.props.onChangeText()
    }

    render() {
        return (
            <TextInput
                style={[styles.textinput, this.props.styles]}
                placeholder={this.props.placeholder}
                placeholderTextColor={colors.text}
                secureTextEntry={this.props.password}
                value={this.state.value}
                onChangeText={this.onChangeText}
              />
        );
    }
}

相关问题