Reactjs usestate逻辑在其他js文件中,HTML逻辑在jsx文件中。

huangapple go评论69阅读模式
英文:

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(&quot;&quot;);
const [disablebtn, disableButton] = useState(true);

const triggerChange = (e) =&gt; {
	const value = e.target.value;
	setValue(value);
	if () {
		disableButton(false);
	} 
};

sample.jsx

const app = () =&gt; {
return (
&lt;&gt;
&lt;input type=&quot;text&quot; onChange={triggerChange } value={value} /&gt;
&lt;Button disabled={disablebtn} &gt;&lt;/Button&gt;
&lt;/&gt;

)
}

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:

Reactjs usestate逻辑在其他js文件中,HTML逻辑在jsx文件中。

huangapple
  • 本文由 发表于 2023年3月23日 09:56:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75818691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定