我对React Native真的很陌生,我想知道如何隐藏/显示组件。 下面是我的测试用例:

<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。

我不知道如何“访问”TouchableHighlight组件,以便隐藏/显示它在我的函数showCancel/ hideccancel中。 此外,我如何从一开始就隐藏按钮?


当前回答

checkincheckout = () => {
        this.setState({ visible: !this.state.visible })
}

render() {
        return (
{this.state.visible == false ?
        <View style={{ alignItems: 'center', flexDirection: 'row', marginTop: 50 }}>

        <View style={{ flex: 1, alignItems: 'center', flexDirection: 'column' }}>

            <TouchableOpacity onPress={() => this.checkincheckout()}>

                <Text style={{ color: 'white' }}>Click to Check in</Text>

            </TouchableOpacity>

        </View>

    </View>
:
<View style={{ alignItems: 'center', flexDirection: 'row', marginTop: 50 }}>

<View style={{ flex: 1, alignItems: 'center', flexDirection: 'column' }}>

   <TouchableOpacity onPress={() => this.checkincheckout()}>

        <Text style={{ color: 'white' }}>Click to Check out</Text>

    </TouchableOpacity>

</View>

</View>
 }

);
}

这一切。享受你的编码……

其他回答

我也有同样的问题,我想要显示/隐藏视图,但我真的不希望UI在添加/删除东西或必须处理重新渲染时跳来跳去。

我写了一个简单的组件来处理它。默认为动画,但易于切换。我把它放在GitHub和NPM上,但所有的代码都在下面。

NPM install——save react-native- hidden -view

import React, { Component, PropTypes } from 'react';
import { Animated  } from 'react-native';

class HideableView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      opacity: new Animated.Value(this.props.visible ? 1 : 0)
    }
  }

  animate(show) {
    const duration = this.props.duration ? parseInt(this.props.duration) : 500;
    Animated.timing(
      this.state.opacity, {
        toValue: show ? 1 : 0,
        duration: !this.props.noAnimation ? duration : 0
      }
    ).start();
  }

  shouldComponentUpdate(nextProps) {
    return this.props.visible !== nextProps.visible;
  }

  componentWillUpdate(nextProps, nextState) {
    if (this.props.visible !== nextProps.visible) {
      this.animate(nextProps.visible);
    }
  }

  render() {
    if (this.props.removeWhenHidden) {
      return (this.visible && this.props.children);
    }
    return (
      <Animated.View style={{opacity: this.state.opacity}}>
        {this.props.children}
      </Animated.View>
    )
  }
}

HideableView.propTypes = {
  visible: PropTypes.bool.isRequired,
  duration: PropTypes.number,
  removeWhenHidden: PropTypes.bool,
  noAnimation: PropTypes.bool
}

export default HideableView;
// You can use a state to control wether the component is showing or not
const [show, setShow] = useState(false); // By default won't show

// In return(
{
    show && <ComponentName />
}

/* Use this to toggle the state, this could be in a function in the 
main javascript or could be triggered by an onPress */

show == true ? setShow(false) : setShow(true)

// Example:
const triggerComponent = () => {
    show == true ? setShow(false) : setShow(true)
}

// Or
<SomeComponent onPress={() => {show == true ? setShow(false) : setShow(true)}}/>

大多数时候我是这样做的:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isHidden: false};
    this.onPress = this.onPress.bind(this);
  }
  onPress() {
    this.setState({isHidden: !this.state.isHidden})
  }
  render() {
    return (
      <View style={styles.myStyle}>

        {this.state.isHidden ? <ToHideAndShowComponent/> : null}

        <Button title={this.state.isHidden ? "SHOW" : "HIDE"} onPress={this.onPress} />
      </View>
    );
  }
}

如果你是编程新手,这一行对你来说一定很陌生:

{this.state.isHidden ? <ToHideAndShowComponent/> : null}

这条线等于

if (this.state.isHidden)
{
  return ( <ToHideAndShowComponent/> );
}
else
{
  return null;
}

但是你不能在JSX内容中编写if/else条件(例如渲染函数的return()部分),所以你必须使用这种符号。

这个小技巧在很多情况下都非常有用,我建议你在开发中使用它,因为你可以快速检查条件。

问候,

编辑:对于更直接的语法,您可以执行{this.state。isHidden && <ToHideAndShowComponent/>}。这里,左操作数在右操作数之前求值,因此如果isHidden为false,则该组件将不显示。

React Native的布局有显示属性支持,类似于CSS。 可能的值:none和flex(默认值)。 https://facebook.github.io/react-native/docs/layout-props#display

<View style={{display: 'none'}}> </View>

在react或react native中,组件隐藏/显示或添加/删除的方式不像android或iOS中那样工作。我们大多数人都认为会有类似的策略

View.hide = true or parentView.addSubView(childView)

但反应的方式是完全不同的。实现这种功能的唯一方法是将组件包含在DOM中或从DOM中删除。

在这个例子中,我将根据单击按钮来设置文本视图的可见性。

这个任务背后的想法是创建一个名为state的状态变量,在按钮单击事件发生时将初始值设置为false,然后它的值切换。现在我们将在创建组件时使用这个状态变量。

import renderIf from './renderIf'

class FetchSample extends Component {
  constructor(){
    super();
    this.state ={
      status:false
    }
  }

  toggleStatus(){
    this.setState({
      status:!this.state.status
    });
    console.log('toggle button handler: '+ this.state.status);
  }

  render() {
    return (
      <View style={styles.container}>
        {renderIf(this.state.status)(
          <Text style={styles.welcome}>
            I am dynamic text View
          </Text>
        )}

        <TouchableHighlight onPress={()=>this.toggleStatus()}>
          <Text>
            touchme
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
}

在这段代码中唯一需要注意的是renderIf,它实际上是一个函数,它将根据传递给它的布尔值返回传递给它的组件。

renderIf(predicate)(element)

renderif.js

'use strict';
const isFunction = input => typeof input === 'function';
export default predicate => elemOrThunk =>
  predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;