I'm really new to React Native and I'm wondering how can I hide/show a component.
Here's my test case:

<TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})} />

<TouchableHighlight 
    onPress={this.hideCancel()}>
    <View>
        <Text style={styles.cancelButtonText}>Cancel</Text>
    </View>
</TouchableHighlight>

我有一个TextInput组件,我想在输入获得焦点时显示TouchableHighlight,然后在用户按下取消按钮时隐藏TouchableHighlight.

I don´t know how to "access" the TouchableHighlight component in order to hide/show it inside of my functions showCancel/hideCancel.
Also, how can I hide the button from the very beginning?

推荐答案

我会这样做:

var myComponent = React.createComponent({

    getInitialState: function () {
        return {
            showCancel: false,
        };
    },

    toggleCancel: function () {
        this.setState({
            showCancel: !this.state.showCancel
        });
    }

    _renderCancel: function () {
        if (this.state.showCancel) {
            return (
                <TouchableHighlight 
                    onPress={this.toggleCancel()}>
                    <View>
                        <Text style={styles.cancelButtonText}>Cancel</Text>
                    </View>
                </TouchableHighlight>
            );
        } else {
            return null;
        }
    },

    render: function () {
        return (
            <TextInput
                onFocus={this.toggleCancel()}
                onChangeText={(text) => this.doSearch({input: text})} />
            {this._renderCancel()}          
        );
    }

});

React-native相关问答推荐

错误:HostBody::get for prop NativeUnimoduleProxy中出现异常- Android虚拟设备(AVD)使用Expo测试React Native App时崩溃

如何在Recact Native中单击Back按钮后调用函数

React onPress 立即执行(渲染时间),但是一旦用箭头函数替换它就不起作用

在 ReactNative 中调用 RCTDeviceEventEmitter.emit 时出错

如何在react-native 中从 FlatList 中删除元素/索引?

react-navigation中的React-native android后退按钮

无法在 React Native iOS 模拟器中按 URI 显示图像

react-native: 'adb' 不是内部或外部命令、可运行程序或批处理文件

使用直接在 Windows 中运行的模拟器在 WSL 中运行 React Native

如何解决此错误您可能需要适当的加载程序来处理此文件类型

textAlignVertical不是有效的样式属性

如何渲染多行文本组件,行间有白色间隙

React-native Xcode 构建失败 -> 'RCTAssert.h file not found'

Ipad 上的 React Native - 错误 - could not connect to development server

React Native 得到这个错误'Unrecognized operator abs'

React-Native:更改 ImageBackground 的不透明度 colored颜色

我们可以在 react webapp 和 react native 应用程序之间共享代码吗,并且可以在 react-native 生产环境中使用

React Native:并排对齐两个 TextInput

React Native font outline / textShadow

React Native 多行TextInput,文本居中