react antd 新增编辑使用同一个组件,怎么动态修改title的值
时间: 2024-03-08 17:50:00 浏览: 16
在 React 中,如果新增和编辑使用同一个组件,可以通过 props 来动态传递 title 的值。具体来说,你可以在父组件中定义 title 的值,然后通过 props 传递到子组件中,并在子组件中修改 document.title。
例如,你可以在父组件中定义一个 state 变量 `isEdit` 来表示当前是新增还是编辑,然后通过条件渲染的方式将 title 的值传递到子组件:
```javascript
class ParentComponent extends React.Component {
state = {
isEdit: false, // 是否为编辑状态
title: "" // 标题
}
render() {
const { isEdit, title } = this.state;
return (
<div>
{isEdit ? (
<ChildComponent title={`编辑 ${title}`} />
) : (
<ChildComponent title={`新增 ${title}`} />
)}
</div>
);
}
}
```
然后,在子组件中,你可以通过 props 来获取 title 的值,并在组件的生命周期函数中动态修改 document.title:
```javascript
class ChildComponent extends React.Component {
componentDidMount() {
document.title = this.props.title;
}
render() {
return (
// 子组件的内容
);
}
}
```
这样,当父组件的 state 变量 `isEdit` 发生变化时,title 的值也会动态改变,并且在组件挂载后,浏览器的 title 也会随之修改。