reactjs - 将函数传递给 React Navigation 的 headerTitle 组件
问题描述
我正在尝试实现一个 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
,这就是您在标题组件中设置函数的方式。
- 你必须在你的类中定义函数
- 在您
componentDidMount
将函数设置为参数时,使用setParam
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
您可以在此处阅读有关导航标题中设置功能的更多信息
推荐阅读
- algorithm - 寻找有向图根的算法
- mongodb - Mongodb用结果数组返回每个不同的项目
- azure - 在故障转移组下升级 Azure SQL Server 定价层
- go - 在我获得用户输入之前,TCP 连接正在关闭
- html - 对齐下拉菜单中的文本
- kubernetes - kubectl apply 不会更新服务选择器标签
- ios - 为什么 HTML5 Media Source 视频不能在 IOS 上运行?
- amazon-s3 - 在不同的 IAM 角色下运行 AWS Lambda 函数
- r - 在使用 R 中的 igraph 生成 k-正则图时,每个 k-正则图是否都是唯一且非随机的?
- ios - 将 Timer 添加到主 RunLoop 是正确的解决方案吗?