英文:
Reactjs usestate logic in other js file and html logic in jsx file
问题
sample.js
const [value, setValue] = useState("");
const [disablebtn, disableButton] = useState(true);
const triggerChange = (e) => {
const value = e.target.value;
setValue(value);
if () {
disableButton(false);
}
};
sample.jsx
const app = () => {
return (
<>
<input type="text" onChange={triggerChange} value={value} />
<Button disabled={disablebtn}></Button>
</>
)
}
export default app;
Please note that I left the condition inside the if
statement empty, as it was in the original code. You may need to add a condition there as needed.
英文:
I want to write usestate login in other js file and html code in the jsx file. Is it possible?
sample.js
const [value, setValue] = useState("");
const [disablebtn, disableButton] = useState(true);
const triggerChange = (e) => {
const value = e.target.value;
setValue(value);
if () {
disableButton(false);
}
};
sample.jsx
const app = () => {
return (
<>
<input type="text" onChange={triggerChange } value={value} />
<Button disabled={disablebtn} ></Button>
</>
)
}
export default app;
答案1
得分: 1
你可以将其制作成自定义钩子:https://react.dev/learn/reusing-logic-with-custom-hooks
但只有在钩子将是可重用的情况下才应这样做。如果此代码仅由此组件使用,那么请将其写在组件中。在React中,混合HTML(JSX)和逻辑是可以预期的:
英文:
You can make it a custom hook: https://react.dev/learn/reusing-logic-with-custom-hooks
Though you should only do this if the hook will be reusable. If this code is only ever used by this component, then write it in the component. Mixing html(jsx) and logic is expected in react:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论