如何在React SPFX中重新渲染子组件?

时间:2019-04-24 09:59:39

标签: reactjs sharepoint spfx

我有一个子组件,该子组件由带有输入标签的表单组成。我在父级中渲染此组件。我想在更改下拉值时用新值重新渲染子组件。

export interface INewFormProperties {
data:any[];
allNames:any[];
allData :any[];
selectedId:any;

 }
export default class NewForm extends React.Component<any, INewFormProperties> {
    constructor(props: any) {
      super(props);
      console.log(this.props.data);
      console.log(this.props.allNames);
      console.log(this.props.selectedId);

  }
 render() {
      return <div className="row">
       <div className="form-group col-md-4">
    <label>Name:<i><b>*</b></i></label>

<select className="form-control formControl" onChange= { () =>
                    this.props.simplifiedFunction()} id="ddlName" defaultValue={this.props.data[0].EmployeeID} >
{this.props.allNames}
</select>
</div> <div className="form-group col-md-4">
<label>Title:</label>
  <input className="form-control formControl" value={this.props.data[0].Title}  id="txtTitle"
   />
</div>
    <div className="form-group col-md-4">
    <label>Department:</label>
    <input className="form-control formControl" value={this.props.data[0].Department} id="txtDepartment" />
</div></div>
}

 }

在父组件中:      私人renderUpdateItems():JSX.Element {

  var selectedId = this.state["selectedEOYID"];
    var data= {};
     if(this.state["isUPdate"]){
        alert("New Update...");
     }
    data = this.state["Items"].filter(item => item.ID == 25);
    return <div>
     <NewForm data={data} allNames={this.state["allNames"]} 
  simplifiedFunction = {this.updateFormDataNew} allData={this.state["Items"]} selectedId={this.state["selectedEOYID"]}></NewForm>

}

private updateFormDataNew(){
   var data = {};
   var selectedId = document.getElementById('ddlName')["value"];
   parentRef.setState({selectedEOYID:selectedId});
}

我正在更改作为子级组件中的属性传递的父级组件的状态,但是在更改状态时,子级组件应重新呈现?

1 个答案:

答案 0 :(得分:1)

是的,如果更改其子项,子项应重新渲染。设置新状态时,请检查状态是否已更改以及在父组件中调用了render函数。我认为您对parentRef有疑问。解决方法如下:

  1. 不要滥用参考文献。 (click here to read React doc about refs

尝试更改

parentRef.setState({selectedEOYID:selectedId});

this.setState({selectedEOYID:selectedId});
  1. 此外,您无需使用文档API(click here to read more about forms in React and how to work with select)即可获得选择的值

您可以更改

onChange= { () => this.props.simplifiedFunction()}

onChange={this.props.simplifiedFunction}

并像这样重写您的updateFormDataNew函数

private updateFormDataNew(event){
   var selectedId = event.target.value;
   this.setState({selectedEOYID:selectedId});
}

请尝试执行此操作。如果这样做没有帮助,请提供“父组件”的构造函数和渲染函数。