有一个名为toggle的功能组件,需要添加一个补丁请求,这样每当toggle触发时,更改都会在UI和数据库中更新(显示/隐藏(。唯一的方法是使用hoots useState吗?
这是一些代码供参考
const ToggleStats = ({ label, value, onChange }) => {
const toggled = !!value
const handleToggle = () => {
onChange(!toggled)
// TODO when the toggle gets clicked a request gets send to update the bd (show/hide)
api.patch(`admin/admin/institutions/id/?with_deleted=true`, { body })
.then(res => res.json())
.then(data => {
this.setState({ })
})
}
return (
<Toggle
label={label}
labelPosition='left'
labelStyle={styles.label}
iconStyle={styles.ripple}
thumbSwitchedStyle={styles.toggle}
trackSwitchedStyle={styles.toggleBackround}
onToggle={handleToggle}
/>
)
}
ToggleStats.propTypes = {
label: PropTypes.string.isRequired,
value: PropTypes.any,
onChange: PropTypes.func.isRequired
}
任何帮助都将不胜感激。
您的问题有点不清楚,但我猜您只是想使用useState来管理显示或隐藏。
const Switch = ({isOn, handleToggle}) => {
return (
<>
<input
checked={isOn}
onChange={handleToggle}
className="react-switch-checkbox"
id={`react-switch-new`}
type="checkbox"
/>
<label className="react-switch-label" htmlFor={`react-switch-new`}>
<span className={`react-switch-button`} />
</label>
</>
)
}
function App() {
const [show, setshow] = React.useState(false)
return (
<div>
<div className="app">
<Switch isOn={show} handleToggle={() => setshow(!show)} />
</div>
{show ? 'Toggled' : null}
</div>
)
}
在我的示例中,您可以看到我通过使用react hook useState来管理父应用程序组件中的显示状态。在点击切换时,现在将show设置为true或false,并且我现在可以使用该状态在我的情况下运行逻辑;在屏幕上切换。