尝试从表单的onSubmit事件处理程序返回jsx

时间:2019-05-16 07:49:34

标签: reactjs forms jsx onsubmit

我正在尝试获取某种形式的jsx onSubmit ...在这里我已将事件处理程序称为initialState

我拥有计算功能,并且在记录日志时也显示在控制台中,但无法返回jsx并在屏幕上显示

RenderSub类扩展了React.Component {

constructor(props) {
    super(props);
    this.state = {
        marks: [{mark: ''}]
    }
}   

initialState = e => {
    e.preventDefault();
    // e.target.reset();
    let totalCreditScored = 0;
    let totalCredits = 0;
    let credit = this.props.lists.credits[this.props.lists.sem];
    for(let i = 0; i < this.state.marks.length; i++) {
        let x = this.state.marks[i].mark / 10;
        if(Number.isInteger(x)) {
            x = x + 1;
        } else {
            x = Math.ceil(x);
        }
        totalCreditScored = totalCreditScored + (x * credit[i]);
        totalCredits = totalCredits + 10 * credit[i];
    }
    let gpa = ((totalCreditScored / totalCredits) * 10).toFixed(2);
    this.setState({marks: [{mark: ''}]});
    console.log(gpa);
    return (
        <div>
            <h3>Your gpa is: {gpa}</h3>
        </div>
    );
}

render() {

    if(this.props.lists.sem === '') {
        console.log("hello");
        return <div></div>;

    }

    return (
        <div>
            <form onSubmit={this.initialState}>
                {this.renderedLists()}
                <button type="submit">Submit</button>
            </form>
        </div>
    );
}

}

分支CSE其他 操作系统 - 计算机图形学和多媒体系统- 编译器设计- 软件工程 - 计算机网络 - 操作系统实验室- 编译器实验室- 网络实验室- 专业培训-I- 提交 您的gpa为:6.7

1 个答案:

答案 0 :(得分:3)

onSubmit调用的操作不应返回任何JSX。相反,它应该更新组件state中的某些属性,然后JSX应该根据state

中的这些更改重新呈现

类似的东西:

constructor(props) {
    super(props);
    this.state = {
        marks: [{mark: ''}]
    }
}   

initialState = e => {
    e.preventDefault();
    // e.target.reset();
    let totalCreditScored = 0;
    let totalCredits = 0;
    let credit = this.props.lists.credits[this.props.lists.sem];
    for(let i = 0; i < this.state.marks.length; i++) {
        let x = this.state.marks[i].mark / 10;
        if(Number.isInteger(x)) {
            x = x + 1;
        } else {
            x = Math.ceil(x);
        }
        totalCreditScored = totalCreditScored + (x * credit[i]);
        totalCredits = totalCredits + 10 * credit[i];
    }
    let gpa = ((totalCreditScored / totalCredits) * 10).toFixed(2);
    this.setState({marks: [{mark: ''}], gpa});
    console.log(gpa);
}

render() {

    if(this.props.lists.sem === '') {
        console.log("hello");
        return <div></div>;

    }

    if(this.state.gpa) {
      return (
        <div>
          <h3>Your gpa is: {gpa}</h3>
        </div>
      )
    }

    return (
        <div>
            <form onSubmit={this.initialState}>
                {this.renderedLists()}
                <button type="submit">Submit</button>
            </form>
        </div>
    );
}