如何在React Native中区分不同的父类

时间:2018-09-23 22:43:22

标签: react-native wrapper

说我有这个包装器组件:

export class WrapperComponent extends React.Component {

    constructor(props) {
        super(props);

        this.opacity = 1
        this.editable = true
        this.placeholder = ''

        this.state = {
            text: ''
        }
    }

    makeInvisible() {
        this.opacity = 0
        this.editable = false
    }
    makeVisible() {
        this.opacity = 1
        this.editable = true
    }

    setPlaceHolder(placeHolder) {
        this.placeHolder = placeholder
    }

    getText() {
        return this.state.text
    }

    render() {
        return (
            <View style = {styles.horizontalView}>
                {this.props.children}
                <TextInput
                    placeholder = "day"
                    style={styles.textInput}
                    opacity = {this.opacity}
                    editable = {this.editable}

                    onChangeText = {(text) => {
                        this.setState({text: text })

                    }}
                />
            </View>
        )
    }
}

我还有另一个使用WrapperComponent类的类,如下所示:

export class ClassUsingWrapperComponent extends React.Component {

    this.wrapper = new WrapperComponent()
    this.wrapper.makeInvisible()
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <WrapperComponent>

            </WrapperComponent>

            <WrapperComponent>

            </WrapperComponent>

            <WrapperComponent>

            </WrapperComponent>


        )
    }
}

我在这里有三个WrapperComponents,但我只想使一个不可见,而让其他可见。我该如何区分哪个WrapperComponent不可见?

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

opacityeditable应该是WrapperComponent的道具,您可以只拥有visible道具并以这种方式渲染多个包装器:

 render() {
     return (
         <WrapperComponent visible />
         <WrapperComponent visible={false} />
     )
 }

,然后在您的WrapperComponent中:

render() {
    return (
        <View style = {styles.horizontalView}>
            {this.props.children}
            <TextInput
                placeholder = "day"
                style={styles.textInput}
                opacity = {this.props.visible? 1 : 0}
                editable = {this.props.visible}

                onChangeText = {(text) => {
                    this.setState({text: text })

                }}
            />
        </View>
    )
}

然后应删除makeInvisiblemakeVisible方法

如果有任何疑问,可以看看React Native props docs