reactjs - 将函数传递到 React Navigation 的 headerTitle 组件中

标签 reactjs react-native react-navigation

我正在尝试实现一个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-navigation 时,这就是您在 header 组件中设置函数的方式。

  1. 您必须在类中定义该函数
  2. componentDidMount 中使用 setParam 将函数设置为参数
  3. 在导航 header 中使用 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中阅读有关设置功能的更多信息。

关于reactjs - 将函数传递到 React Navigation 的 headerTitle 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55008102/

相关文章:

ios - 找不到 -lRCTGeolocation 的库

react-native - Android ScrollView 忽略其边框(附截图)

javascript - 异常在 promise 链中被吞没

react-native - 在 React-Native navigationOptions 中处理 OnPress

android - react 导航从嵌套导航器更改 Activity 选项卡

reactjs - 何时以及如何在react/router/redux应用程序中获取详细 View 的数据?

reactjs - 处理 FormControl React 的更改

javascript - react : Take input file when link is clicked in function component

reactjs - 在 StackNavigator 中使用自定义选项卡?

reactjs - 测试 React 组件方法正在调用函数 pass 作为 prop