将函数传递给React Navigation的headerTitle组件

问题描述 投票:1回答:1

我正在尝试实现一个deletePost按钮,但我很难将它传递到我的头部组件中。这是

export class PostScreen extends Component {


  // Custom headerTitle component.
  static navigationOptions = ({ navigation }) => {
    const { params } = navigation.state;
    return { headerTitle: <PostTitle {...params} handleDelete={this.handleDelete}/> }
  };

  handleDelete = async (id) => {
    const { deletePost } = this.props;
    const token = await AsyncStorage.getItem('token');
    deletePost(token, id);
  }

render() {

这似乎不是传递它的正确方法。什么是正确的方法?我在文档中找不到任何内容。

reactjs react-native react-navigation
1个回答
4
投票

当您使用react-navigation时,这就是您在标头组件中设置函数的方法。

  1. 您必须在班级中定义该功能
  2. 在你的componentDidMount中使用setParam将函数设置为参数
  3. 在导航标题中使用getParam

这就是它在一个非常简单的组件中的外观。

export default class Screen1 extends React.Component {

  static navigationOptions = ({ navigation }) => {
    const { params } = navigation.state; // this is included because you had added it and you may require the params in your component
    return {
      headerTitle: <PostTitle  {...params} handleDelete={navigation.getParam('handleDelete')} />, // grab the function using getParam
    };
  };

  handleDelete = () => {
    alert('delete')
  }

  // set the function as a param in your componentDidMount
  componentDidMount() {
    this.props.navigation.setParams({ handleDelete: this.handleDelete });
  }


  render() {
    return (
      <View style={styles.container}>
        <Text>Screen1</Text>
      </View>
    )
  }
}

然后在你的PostTitle组件中,你可以通过调用this.props.handleDelete来使用你刚刚传递的函数

这是一个小吃,显示基本功能https://snack.expo.io/@andypandy/functions-in-a-navigation-header

您可以在导航标题here中阅读有关设置功能的更多信息


0
投票

在您的组件中,挂载使用如下所示的箭头函数,并且在组件首次安装时不会调用该函数。

componentDidMount() {
    this.props.navigation.setParams({ handleDelete: (() => this.handleDelete()) 
});
© www.soinside.com 2019 - 2024. All rights reserved.