IMO,React是一种非常适合于从道具中选择使用值或使用自己状态的模式,但是当我有条件地使用钩子时,棉线出现了一些错误。
我试着使用钩子,条件如下,但使用的是eslint错误React hook useState is called conditionally。根据这个医生的解释,React relies on the order in which Hooks are called。
const Counter = ({ value, onChange, defaultValue = 0 }) => {
const [count, onCountChange] =
typeof value === "undefined" ? useState(defaultValue) : [value, onChange];
return (
<div>
{count.toString()}
<button
onClick={() => {
onCountChange(count + 1);
}}
>
+
</button>
</div>
);
};
function App() {
const [count, onCountChange] = useState(0);
return (
<div className="App">
<div>
Uncontrolled Counter
<Counter />
</div>
<div>
Controlled Counter
<Counter value={count} onChange={onCountChange} />
</div>
</div>
);
}如何使用钩子来实现与下面类组件相同的功能?
class CounterClass extends React.Component {
state = {
value: this.props.defaultValue || 0
};
render() {
const isControlled = typeof this.props.defaultValue === "undefined";
const count = isControlled ? this.props.value : this.state.value;
return (
<div>
{count.toString()}
<button
onClick={() => {
isControlled &&
this.props.onChange &&
this.props.onChange(this.props.value + 1);
!isControlled && this.setState({ value: this.state.value + 1 });
}}
>
+
</button>
</div>
);
}
}或者这种道具/状态在一个组件中的可选方式是错误的?
我学习了"defaultValue"、"value"、"onChange" API的命名以及从React <input>组件中学到的思想。
发布于 2019-04-17 15:06:38
您可以将组件拆分为完全控制和完全不受控制的组件。演示
const CounterRepresentation = ({ value, onChange }) => (
<div>
{value.toString()}
<button
onClick={() => {
onChange(value + 1);
}}
>
+
</button>
</div>
);
const Uncontrolled = ({ defaultValue = 0 }) => {
const [value, onChange] = useState(defaultValue);
return <CounterRepresentation value={value} onChange={onChange} />;
};
// Either use representation directly or uncontrolled
const Counter = ({ value, onChange, defaultValue = 0 }) => {
return typeof value === "undefined" ? (
<Uncontrolled defaultValue={defaultValue} />
) : (
<CounterRepresentation value={value} onChange={onChange} />
);
};https://stackoverflow.com/questions/55730352
复制相似问题