[英]How can I render some JSX with onClick event?
So I'm trying to render some JSX when a user presses a button, I'm trying to do this via onClick but it is not working, The JSX does not get rendered on the screen.因此,当用户按下按钮时,我尝试渲染一些 JSX,我尝试通过 onClick 执行此操作,但它不起作用,JSX 不会在屏幕上渲染。 Is there a way to do this?有没有办法做到这一点? My code is like this:我的代码是这样的:
function RandomScreen() {
async function HandleClick() {
// make API post request
.then(function(response) {
return (<h1>{response.data}</h1>)
})
}
return (
<button onClick={HandleClick}>Click me</button>
)
}
I think you are looking for something like this:我想你正在寻找这样的东西:
function RandomScreen() {
const [data, setData] = useState(null);
async function HandleClick() {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((json) => {
console.log(json);
setData(json);
});
}
return (
<button onClick={HandleClick}>
Click me
{data && <h1>{JSON.stringify(data, null, 2)}</h1>}
</button>
);
}
store your data in a state for example例如,将您的数据存储在 state
const [data, setData] = React.useState();
...
.then(function(response) {
setData(response.data);
})
and in JSX you can handle the display part:在 JSX 中你可以处理显示部分:
{data && <h1>{data}</h1>}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.