【问题标题】:When I click on a link, how can I change the status of another component?当我单击一个链接时,如何更改另一个组件的状态?
【发布时间】:2019-12-29 13:47:25
【问题描述】:

当我单击一个按钮时,它会将我重定向到另一个组件 (#2),其中有两种状态,并根据哪种状态显示一种或另一种内容。组件(#2)的默认状态是 true,我需要知道如何做的是单击组件(#1)的按钮将状态更改为 false。

这是一个 ReactJs 应用程序,我使用函数组件,钩子,没有类组件

Thats the button code:
<Link to="/register">
<button className="btn btn-success btnVerde">
</button>
</Link>

Thats the component#2:
const [state, setState] = React.useState(true);
{state && <div1......../>}
{!state && <div2......./>}

我希望单击组件#1 中的按钮,它会重定向到组件#2,默认状态如何为 true,然后将其更改为 false

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您可以处理 Component1 中的状态,并在您的 onClick 调用 setState 中使用相反的值更新值,如下所示:

    <button onClick={() => setState({state: !state})}>Click</button>
    

    并在component2中将值作为prop接收,例如:

    const Component2 = ({showCustom}) => showCustom ? <span> Custom </span> : <span>No Custom</span>;
    

    【讨论】:

    • 您好,感谢您的想法,它帮助我找到了解决方案,与您不完全一样,但方式相同。我正在使用 redux 和 typescript,所以我必须创建、键入、操作、接口和 reducer 才能将状态保存在 redux 中,稍后将在第二个组件上使用。所以在 compnent#1 我做了: const change = () => props.changeState(false);并在组件#2 useEffect(() => { if(props.booleanState){ showCompanyRegister() } else { showTalentRegister() } }, []);
    【解决方案2】:

    感谢@rcoro,这就是我解决问题组件#1 的方法:

    const change = () => props.changingState(false);
    <Link to="/register"><button onClick={change}className="btnPink">
             {t("talents_btnReserve")}
            </button>
            </Link>
    

    组件#2:

    const showTalentRegister = () => setState(true);
    const showCompanyRegister = () => setState(false);
    
    useEffect(() => {
    if(props.booleanState){
      showCompanyRegister()
    }
    else {
      showTalentRegister()
    }
    

    }, []);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2022-01-06
      • 1970-01-01
      • 2018-05-05
      相关资源
      最近更新 更多