0

我有一个用于 Success 的通用组件,并通过导航路线呈现该组件。

成功组件.jsx

var pageTitle;
const SuccessComponent = (props) => {
  pageTitle = props.location.state.title;
  return(
    <> jsx code here </> 
  )
}

//This title needs to be dynamic, not getting props here hence took var pageTitle but getting undefined.
let SuccessComp = withTitle({component: SuccessComponent, title: pageTitle})
export default SuccessComp;

WithTitle 组件通过 react-helmet 库设置标题并在每个屏幕上更新。我需要更改 SuccessComponent 不同调用的标题。我怎样才能做到这一点?

我正在使用 SuccessComponent 如下。

我的组件.jsx

export default MyComponent = () => {
  const onSubmit = () => {
    props.history.push({pathname:'/success',state:{title: 'my comp'})
  }
  return(
    <> jsx code here </>
  )
}

MyComponent1.jsx

export default MyComponent1 = () => {
  const onSubmit = () => {
    props.history.push({pathname:'/success',state:{title: 'my comp 1'})
  }
  return(
    <> jsx code here </>
  )
}

withTitle.jsx

export default function withTitle({component: Component, title}){
 return function title(props){
  (
   <>
     <Helmet>
        <title>{title}</title>
     </Helmet>
     <Component {...props} />
   </>
   )
  }
}
4

2 回答 2

0

withTitle.jsx

export default function withTitle({component: Component, title}){
const [titleState, setTitleState] = useState();

 return function title(props){
  (
   <>
     <Helmet>
        <title>{title}</title>
     </Helmet>
     <Component {...props} setTitle={setTitleState}/>
   </>
   )
  }
}

添加了一个方法调用并从成功组件中调用它,如下所示。

成功组件

const SuccessComponent = (props) => {
  props.setTitle(props.location.state.pageTitle);
  return(
    <> jsx code here </> 
  )
}

//This title needs to be dynamic, not getting props here hence took var pageTitle but getting undefined.
let SuccessComp = withTitle({component: SuccessComponent })
export default SuccessComp;
于 2020-08-06T06:31:18.363 回答
0

您正在通过 react-router 发送状态,但您尝试访问本地道具。您需要访问标题this.props.location.state.title

如果您查看此答案,它将帮助您获得正确的结论。如何在 react-router v4 中通过 history.push/Link/Redirect 传递参数?

于 2020-08-04T11:23:32.350 回答