【问题标题】:Pass function into React Navigation's headerTitle component将函数传递给 React Navigation 的 headerTitle 组件
【发布时间】:2019-03-05 17:07:43
【问题描述】:

我正在尝试实现一个 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() {

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

【问题讨论】:

  • 您确定这是react-native-navigation 而不是react-navigation
  • @Andrew 对,是react-navigation
  • 你从哪里得到 id?

标签: reactjs react-native react-navigation


【解决方案1】:

当您使用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中阅读有关设置功能的更多信息

【讨论】:

  • 谢谢,它有效。当组件第一次安装时,我仍然得到一个 Failed 道具类型。无论如何我可以在安装之前设置道具吗?
  • 哪个道具失败了?
  • handleDelete 函数。当组件第一次挂载时它不可用,然后 componentDidMount 使其可用
  • 我猜它在 PostTitle 组件中,它抱怨你可以为 prop 设置默认值
  • 这两个中的一个几乎是您的选择。
【解决方案2】:

在您的组件中安装时使用了如下箭头函数,并且在组件第一次安装时不会调用该函数。

componentDidMount() {
    this.props.navigation.setParams({ handleDelete: (() => this.handleDelete()) 
});

【讨论】:

    猜你喜欢
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    相关资源
    最近更新 更多