reactjs - reactjs——点击按钮,从localstorage加载一些东西,并在函数外显示
问题描述
我不知道这个话题是否有意义,但我基本上想:
- 点击一个按钮
- 从我的本地存储中加载一些东西
- 用加载的东西替换按钮
我目前有
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}/>
如何用我从通话中得到的东西替换按钮?甚至可能吗?
解决方案
您正在使用无状态功能组件来实现您想要的功能。但是,您需要组件的状态概念,以便能够跟踪它们是否已从本地存储中检索到令牌。这就是为什么在 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
中定义了,则方法仅显示获取的信息。(即本身) 除非它被采取,但是,显示带有按钮的初始界面。state
render()
token
推荐阅读
- ios - 使用 AFNetworking 进行 SSL 固定不起作用
- xcode - 如何在 Xcode 导航面板中使用键盘将光标放在当前突出显示的文件上
- javascript - 有两个条件有条件地渲染工具提示
- .htaccess - htaccess 不允许访问文件
- laravel - 单击连线后 x 数据值重置:click.prevent 操作
- css - 如何在其jspui版本上将DSpace中发现(搜索结果)页面中侧边栏的默认位置从右侧更改为左侧?
- javascript - 如何将对象数组转换为表单数据?
- microstrategy - 订单日期之间的时间
- python-3.6 - 使用 python youtube_dl 将数据直接下载到临时文件中
- ada - 元素太多的数组只有编译器警告?