为什么在react中实现useState时显示"无效钩子调用"错误



我正在尝试在react中实现useState,但我得到了错误的Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:这是我尝试实现的代码。帮助我如何解决这个问题

import React, { useState, useEffect, Component } from "react";
import ReactDOM from "react-dom";
class Demo extends Component {
render() {
const [fromDate, setFromDate] = useState("");
const [toDate, setToDate] = useState("");
const assignFromDate = e => {
console.log(e.target.value);
setFromDate(e.target.value);
};
return (
<div className="App">
<div className="col-sm-4">
<div className="form-group">
<span style={{ opacity: "0.6", fontSize: "13px" }}>from</span>
<input
type="date"
name="from"
id="startdate"
value={fromDate}
onChange={assignFromDate}
className="form-control datepicker"
style={{ width: "150px" }}
/>
</div>
</div>
<div className="col-sm-4">
<div className="form-group">
<span style={{ opacity: "0.6", fontSize: "13px" }}>to</span>
<input
type="date"
name="to"
min={fromDate}
id="enddate"
value={toDate}
placeholder="Select Date"
onChange={e => setToDate(e.target.value)}
className="form-control datepicker"
style={{ width: "150px" }}
/>
</div>
</div>
</div>
);
}
}
export default Demo;

您必须使用functional组件而不是class组件。

以下是您的工作演示:https://stackblitz.com/edit/react-ekfzud

import React, { useState, useEffect, Component } from "react";
import ReactDOM from "react-dom";
function Demo(){
const [fromDate, setFromDate] = useState("");
const [toDate, setToDate] = useState("");
const assignFromDate = e => {
console.log(e.target.value);
setFromDate(e.target.value);
};
return (
<div className="App">
<div className="col-sm-4">
<div className="form-group">
<span style={{ opacity: "0.6", fontSize: "13px" }}>from</span>
<input
type="date"
name="from"
id="startdate"
value={fromDate}
onChange={assignFromDate}
className="form-control datepicker"
style={{ width: "150px" }}
/>
</div>
</div>
<div className="col-sm-4">
<div className="form-group">
<span style={{ opacity: "0.6", fontSize: "13px" }}>to</span>
<input
type="date"
name="to"
min={fromDate}
id="enddate"
value={toDate}
placeholder="Select Date"
onChange={e => setToDate(e.target.value)}
className="form-control datepicker"
style={{ width: "150px" }}
/>
</div>
</div>
</div>
);
}
export default Demo;

useState将仅在功能组件内部工作。因此,最好将输入移动到一个表示协同组件,并在那里使用fromDate,toDate。

const Input = (props) => {
return
(<input
type="date"
name="to"
min={fromDate}
id="enddate"
value={toDate}
placeholder="Select Date"
onChange={e => this.props.setToDate(e.target.value)}
className="form-control datepicker"
style={{ width: "150px" }} />);
}
<Input setToDate ={this.setToDate.bind(this)}/>

相关内容

  • 没有找到相关文章

最新更新