我想在navigationOptions中访问我的组件状态。我试图将它分配给componentDidMount中的params。它仍然没有奏效。如何设置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")}
/>
)
};
};
}
我可以使用任何标准方法来实现这一目标吗?
答案 0 :(得分:8)
每当状态发生变化时,您都需要致电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,
});
};
答案 1 :(得分:0)
在此处输入代码
this.state = {
notifyCont: 4
};
headerRight: (
<Text style={{fontSize: 10}}>{navigation.getParam('number')}</Text>
</View>
),
componentDidMount
this.props.navigation.setParams({
number: this.state.notifyCont,
});