首页 > 解决方案 > reactjs——点击按钮,从localstorage加载一些东西,并在函数外显示

问题描述

我不知道这个话题是否有意义,但我基本上想:

  1. 点击一个按钮
  2. 从我的本地存储中加载一些东西
  3. 用加载的东西替换按钮

我目前有

const getToken = (props) => {
    let token = localStorage.getItem("token");
    console.log('token', token);
    return token;

}

const ApiInstruction = (props) => (
    <div>
        <Backdrop show={props.show} clicked={props.modalClosed}/>

        <div className="api-instruction"
             style={{transform: props.show ? 'translateY(0)' : 'translateY(-100vh)',
                     opacity: props.show ? '1': '0'}}>
            <button className="api-instruction-button" onClick={() => getToken(props)}>Request Token</button>
            <h4>Instruction on how to use API:</h4>
            <p>bleh</p>
            <p>(click anywhere in grey to close)</p>
        </div>
    </div>
);

单击按钮会触发该getToken功能,但我不知道如何传回结果。

我目前的ApiInstrction电话如下。

<ApiInstruction show={this.state.openApiInsModal} modalClosed={this.BackdropHandler} token={null}/>

如何用我从通话中得到的东西替换按钮?甚至可能吗?

标签: reactjs

解决方案


您正在使用无状态功能组件来实现您想要的功能。但是,您需要组件的状态概念,以便能够跟踪它们是否已从本地存储中检索到令牌。这就是为什么在 React 中有状态的组件,在这种情况下,你应该使用它,而不是无状态的组件。

下面是一个代码示例,说明了状态的使用如何提供帮助。

class ApiInstruction extends Component {
    state = {
    };

    getToken = (props) => {
        let token = localStorage.getItem("token");
        console.log('token', token);
        return token;
    }

    handleClick = (event) => {
        this.setState({token: getToken(this.props);});
    }

    render() {
        if(this.state.token === undefined) {
            return (
                <div>
                    <Backdrop show={props.show} clicked={props.modalClosed}/>

                    <div className="api-instruction"
                         style={{transform: props.show ? 'translateY(0)' : 'translateY(-100vh)',
                                 opacity: props.show ? '1': '0'}}>
                        <button className="api-instruction-button" onClick={this.handleClick}>Request Token</button>
                        <h4>Instruction on how to use API:</h4>
                        <p>bleh</p>
                        <p>(click anywhere in grey to close)</p>
                    </div>
                </div>
            );
        } else {
            <p>{this.state.token}</p>
        }
    }
}

如您所见,如果在信息token中定义了,则方法仅显示获取的信息。(即本身) 除非它被采取,但是,显示带有按钮的初始界面。staterender()token


推荐阅读