gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:18:22 27 4
gpt4 key购买 nike

我想在 navigationOptions 中访问我的组件状态。我试图将它分配给 componentDidMount 中的参数。仍然没有用。如何将 this.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")}
/>
)
};
};
}

有什么标准方法可以用来实现这一目标吗?

最佳答案

您需要调用 this.props.navigation.setParams每当状态更改以更新 params navigationOptions 中的值:

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

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

关于react-native - 如何在 native react 中访问导航选项中的组件状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50236254/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com