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

pet*_*176 2 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() {
Run Code Online (Sandbox Code Playgroud)

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

And*_*rew 5

在使用时,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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

您可以在此处导航标题中了解有关设置功能的更多信息