如何在react native的导航选项中访问组件状态?

lf5gs5x2  于 2023-05-01  发布在  React
关注(0)|答案(2)|浏览(123)

我想在navigationOptions中访问我的组件状态。我试着把它分配给componentDidMount里面的参数。但还是没有成功。我怎么能设置,这个。state.SearchText作为navigationOptions中的输入值?

export default class WorkoutScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {
      searchText: "Test Text"
    };
  }

  componentDidMount() {
    this.props.navigation.setParams({
      searchWorkouts: this.searchWorkoutHandler
    });
  }

  onChangeSearch = value => {
    this.setState({
      searchText: value
    });
  };

  searchWorkoutHandler = () => {
    alert("Searching Workouts");
  };

  render() {
    return (
      <View>
        <Text style={styles.searchInput}>{this.state.searchText}</Text>
      </View>
    );
  }

  static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;
    alert(params.searchText);

    return {
      headerTitle: (
        <SearchInput
          style={styles.searchInput}
          value={params.searchText}
          source={Search}
          borderRadius={50}
          placeholder="Search / Filter"
          onChangeText={value => this.onChangeSearch(value)}
          onPress={() => params.searchWorkouts()}
        />
      ),
      headerTitleStyle: { width: "100%", alignItems: "center" },
      headerStyle: {
        paddingRight: 10,
        paddingLeft: 10
      },
      headerLeft: (
        <ClickableIcon
          source={Bookmark}
          onIconPressed={() => alert("Notifications Clicked Workout")}
        />
      ),
      headerRight: (
        <ClickableIcon
          source={Movements}
          onIconPressed={() => alert("Add New Clicked")}
        />
      )
    };
  };
}

有没有什么标准的方法可以实现这一点?

2mbi3lxu

2mbi3lxu1#

当状态发生变化时,您需要调用this.props.navigation.setParams来更新navigationOptions中的params值:

componentDidMount() {
  this.props.navigation.setParams({
    searchWorkouts: this.searchWorkoutHandler,
    searchText: this.state.searchText,
  });
}

onChangeSearch = (value) => {
  this.setState({
    searchText: value,
  });
  this.props.navigation.setParams({
    searchText: value,
  });
};
x3naxklr

x3naxklr2#

this.state = {
  notifyCont: 4
};

headerRight: (
      <Text style={{fontSize: 10}}>{navigation.getParam('number')}</Text>
  </View>
),

componentDidMount

this.props.navigation.setParams({
  number: this.state.notifyCont,
});

相关问题