当我从onChange()获得userInput并尝试将其传递给子组件时,它不是在更新,而是保持初始值。 我正在尝试将字符串从输入字段传递给称为Tensor-flow Toxic Model的子组件,但是TensorFlowToxidModel的状态在初始设置后不会更改。所以我不能运行moddl。
class TensorFlowToxicModel extends React.Component<{}, ToxicityModelProp> {
constructor(props: userInput) {
super(props);
this.state = {
modelObjectArray: [],
userSentence: props.userSentence,
};
}
componentDidUpdate(){
console.log("This is from TensorFlowToxicModel Compononent")
console.log("This is the sentence ", this.state.userSentence )
}
renderThePost = () => {
let output = cleanMlOutput(this.state.userSentence)
return output
};
render() {
return (
<div>
<p>This is a Checker Does this even work</p>
</div>
);
}
}
class InputField extends React.Component<{}, userInput> {
constructor(prop: inputFromField) {
super(prop);
this.state = {
userSentence: "",
};
}
handleChange = (event: React.FormEvent<HTMLInputElement>): void => {
let userInputData: string = event.currentTarget.value;
//console.log(event.currentTarget.value);
this.setState({
userSentence: userInputData,
});
};
render() {
const userSentence = {
userSentence:this.state.userSentence
}
//Instead of updating TensorFlowToxicModel Each time from inside its own compnoent
//Call it here each time user types something
return (
<div>
<input id="inputField" onChange={this.handleChange} />
<h4>{this.state.userSentence}</h4>
<TensorFlowToxicModel {...userSentence}/>
</div>
);
}
}
类型
type modelObject = { label: string; resultMatch: boolean; resultProbablity: number; };
type ToxicityModelProp = { userSentence: string; modelObjectArray : modelObject[] }
答案 0 :(得分:1)
您将prop
类型的ToxicityModelProp
放错了位置。它应该放在第一位。阅读docs,了解有关组件道具,状态类型的信息
type ToxicityModelProp = { userSentence: string }
type ToxicityModelState = { modelObjectArray: [] }
class TensorFlowToxicModel extends React.Component<ToxicityModelProp, ToxicityModelState> {
constructor(props: userInput) {
super(props);
this.state = {
modelObjectArray: []
};
}
renderThePost = () => {
let output = cleanMlOutput(this.props.userSentence)
return output
};
render() {
return (
<div>
<p>Sentence is: { this.props.userSentence }</p>
</div>
);
}
}
我已经对您的代码进行了一些更改,并更新了here。看看