在react native中单击按钮时更改状态

时间:2019-11-20 15:39:44

标签: javascript reactjs react-native expo

我是本机反应的新手,只想让一个功能更改所单击按钮的状态,而不要更改其他具有相同功能的按钮 正如我在标题中解释的,这里是示例代码 请任何帮助,我知道这可能是一个棘手的问题,但任何答案都将有所帮助 非常感谢

export default class App extends Component {
  constructor(){
    super();
    this.state = {
      opened: true,
    }
 }


 componentHideAndShow = () =>{
   this.setState(previousState => ({opened: !previousState.opened}))
 }

  render() {
      return (
            {
              this.state.opened ? <Text> hello</Text> : <Text> hello sdfsdfsdf</Text> 
            }
            <Text onPress={this.componentHideAndShow}>test</Text>
            {
              this.state.opened ? <Text> hello</Text> : <Text> hello sdfsdfsdf</Text> 
            }
            <Text onPress={this.componentHideAndShow}>test</Text>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

这应该有效。

import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      opened: [true, true]
    };
  }

  componentHideAndShow = index => {
    const opened = this.state.opened;
    opened[index] = !opened[index];
    this.setState({ opened: opened });
  };

  render() {
    return (
      <View>
        {this.state.opened[0] ? (
          <Text> hello</Text>
        ) : (
          <Text> hello sdfsdfsdf</Text>
        )}
        <Button onPress={() => this.componentHideAndShow(0)}>test</Button>
        {this.state.opened[1] ? (
          <Text> hello</Text>
        ) : (
          <Text> hello sdfsdfsdf</Text>
        )}
        <Button onPress={() => this.componentHideAndShow(1)}>test</Button>
      </View>
    );
  }
}

编辑:如果您不知道项目数,可以这样做:

    import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';

const myArrayOfStrings = ['hello1', 'hello2', 'hello3', 'hello4', 'hello5'];

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      opened: undefined
    };
  }

  componentDidMount() {
    let opened = [];
    myArrayOfStrings.map(item => {
      opened.push(true);
    });
    this.setState({ opened: opened });
  }

  componentHideAndShow = index => {
    const opened = this.state.opened;
    opened[index] = !opened[index];
    this.setState({ opened: opened });
  };

  render() {
    const output = myArrayOfStrings.map((item, index) => {
      return (
        <View>
          <Text>
            {this.state.opened[index]
              ? `${item} is opened`
              : `${item} is opened`}
          </Text>
          <Button onPress={() => this.componentHideAndShow(0)}>test</Button>
        </View>
      );
    });

    return <View>{output}</View>;
  }
}