[英]How to show form after onclick event React
我有一个 React 组件,它返回一个带有按钮的表单。 当我单击按钮时,我希望在同一页面上显示另一个不同的表单。 我怎么做? 单击按钮时如何返回下一个表单? 下面只是一个给出主要思想的例子
function Example() {
return (
<div>
<form>
<button onclick={showForm}></button>
</form>
</div>
)
}
定义一个 state 来处理表单的可见性。
import React, { useState } from 'react';
function Example() {
const [showForm, setShowForm] = useState(false);
const showForm = () => {
setShowForm(!showForm);
}
return (
<div>
<form>
<button onClick={showForm}></button>
</form>
{showForm && (
<form>
...
</form>
)}
</div>
)
}
您可以使用三级运算符。 这是一个示例,您可以使用它从显示一个组件更改为另一个组件。
最初将 state 设置为 false,然后在单击按钮时将其更改为 true,这可以在您的 App.js 中,然后将其传递给呈现它的组件。
const [ editing, setEditing ] = useState(false)
const editRow = user => {
setEditing(true)
setCurrentUser({ id: user.id, name: user.name, username: user.username })
}
初始组件的按钮应该是这样的
<button onClick={() => setEditing(false)} className="button muted-button">
Cancel
</button>
<div/>
在您的主 App.js 中,这是您在两个组件之间切换的方式
<div>
{editing ? : (render what component you want when it is set to true ) : (render the component you want when it is set to false)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.