首页 > 解决方案 > 如何在静态字段中使用反应导航发送值?

问题描述

我有一个屏幕<Switch />使用react navigation.

我知道如何this.state通过 this.props.navigation.setParams.

但我不知道如何将<Switch />值发送到外部函数。

我用代码试试onValueChange={value => params.handleThis(value)}

handleThis但就我而言key-value,它显然无法获得价值。

this.props.navigation.setParams({ handleThis: this.changeSwitch });

如何将<Switch />onChange 值发送到外部函数?

这是我的代码:

      static navigationOptions = ({ navigation }) => {
        const { params = {} } = navigation.state;
        return {
          title: 'Title',
          headerStyle: {
            backgroundColor: ColorSetting.headerColor,
            elevation: null,
          },
          headerTitleStyle: {
            fontWeight: '300',
            fontFamily: 'FFF Tusj',
            fontSize: 18
          },
          headerRight:
            <View style={{ marginRight: 15 }}>
              <Switch
                onValueChange={value => params.handleThis()}
                value={params.switchOn}
                onTintColor='#444444'
                tintColor='#444444'
              />
            </View>,
        };
      };

      constructor(props) {
        super(props);

        this.state = {
          switchOn: false
        };
      }

      componentDidMount() {
        this.props.navigation.setParams({
          handleThis: this.changeSwitch
        });
      }

  changeSwitch = () => {
    const { switchOn, titleVersion } = this.state;

    this.props.navigation.setParams({ switchOn: !switchOn });
    this.setState({ switchOn: !switchOn });
  }

任何帮助,将不胜感激。提前致谢。

标签: react-nativereact-navigation

解决方案


您可以params.handleThis用作处理程序,不需要内联函数。

static navigationOptions = ({ navigation }) => {
  const { params = {} } = navigation.state;
  return {
    title: 'SO Question',
    headerStyle: {
      elevation: null,
    },
    headerTitleStyle: {
      fontFamily: 'FFF Tusj',
      fontSize: 18
    },
    headerRight:
      <View style={{ marginRight: 15 }}>
        <Switch
          onValueChange={params.handleThis}
          value={params.switchOn}
          onTintColor='#444444'
          tintColor='#444444'
        />
      </View>,
  };
};

之后changeSwitch将接收新值作为第一个参数。

changeSwitch = (switchOn) => {   
  this.props.navigation.setParams({ switchOn });
  this.setState({ switchOn });
}

这是一个工作示例


推荐阅读