![](/img/trans.png)
[英]How to render a child component within parent component using react and typescript?
[英]React JS : Calling Child component method within parent component (React with typescript)
我正在嘗試創建一個自定義號碼選擇器組件,並嘗試將其添加到需要的任何位置。 但是,當我嘗試在Parent組件中獲取數字選擇器值時,我得到的是舊值。 有人可以幫我弄這個嗎?
import * as React from "react";
interface IState {
value: number;
}
interface IProps {
setValue(val: number): void;
}
class NumberPicker extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
value: 0
};
}
public doDecrement = () =>
// DECREMENT CODE
{
if (this.state.value < 1) {
console.log("LESS THAN O");
} else {
this.setState({
value: this.state.value - 1
});
this.props.setValue(this.state.value);
}
};
public doIncrement = () =>
// INCREMENT CODE
{
this.setState({
value: this.state.value + 1
});
this.props.setValue(this.state.value);
};
public handleChange = (
e: React.ChangeEvent<HTMLInputElement> // CHANGE HANDLER
) => {
const val = parseInt(e.target.value);
this.setState({ value: val });
};
public render() {
return (
<div>
<button
onClick={this.doDecrement}
className="fa fa-minus fa-inverse fa-2x"
/>
<input
type="text"
className="number"
value={this.state.value}
onChange={this.handleChange}
/>
<button
onClick={this.doIncrement}
className="fa fa-plus fa-inverse fa-2x"
/>
</div>
);
}
}
export default NumberPicker;
import * as React from "react";
import NumberPicker from "./NumberPicker";
interface IState {
val: number;
}
interface IProps {}
class Parent extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
val: 0
};
}
handleVal = (value: number) => {
this.setState({ val: value }, () => console.log(this.state.val));
};
render() {
return (
//Some fields along with the below numberpicker
<NumberPicker setValue={this.handleVal} />
);
}
}
export default Parent;
我也嘗試過使用setState的回調函數,但是它似乎不起作用。 父組件始終顯示較舊的值。如何獲取父內部的NumberPicker的更新值? 幫助將不勝感激!
React的setState
是異步的,因此,在setState
更新子Numberpicker組件中的狀態之前,將調用this.props.setValue
函數。 這就是為什么將舊值傳遞給父組件的原因。
相反,您可以在setState
的回調函數中調用this.props.setValue
。
public doIncrement = () =>
// INCREMENT CODE
{
this.setState({
value: this.state.value + 1
}, () => {
this.props.setValue(this.state.value);
});
};
public doDecrement = () =>
// DECREMENT CODE
{
if (this.state.value < 1) {
console.log("LESS THAN O");
} else {
this.setState({
value: this.state.value - 1
}, () => {
this.props.setValue(this.state.value);
});
}
};
setState不是一個同步函數。 因此,當您從父級調用回調時,您將使用舊的狀態值來調用它,因為新值將在將來的某個時候設置。 您可以使用與狀態相同的值來調用該回調:this.state.value-1或this.state.value +1。它將按預期工作。 我還建議閱讀思考方式,以做出更好的直覺,以了解應該將自己的狀態保持在什么位置。
不要使用狀態在回調中傳遞值,您可以這樣做:-
handleChange = (
e: React.ChangeEvent<HTMLInputElement> // CHANGE HANDLER
) => {
const val = parseInt(e.target.value);
// this.setState({ value: val });
this.props.setValue(val);
};
希望對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.