使用'React.createElement(xxx,{a:this.state.a})'创建组件时,如何动态更新此组件道具?

时间:2019-05-26 01:41:18

标签: reactjs

这是我的错误示​​例。 我想动态添加组件 然后动态更改组件的属性。

但是……

import React from 'react';
export class Test extends React.Component {
    state = { SubArray: [] }
    render() {
        return (
            <div>
                <button onClick={this.F_Add}>Add New Sub</button>
                <div>{this.state.SubArray}</div>
                <button onClick={this.F_ChangeA}>Change Each Value = 100,200,……</button>
                <button onClick={this.F_ChangeB}>Change All value=100</button>
            </div>
        );
    }
    F_Add = () => {
        let NewSub = React.createElement(Subitem, { value: 100 })
        this.state.SubArray.push(NewSub)
        this.setState({ SubArray: this.state.SubArray })
    };
    F_ChangeA = () => {
        let value = 0
        for (var k = 0, length = this.state.SubArray.length; k < length; k++) {
            let input = this.state.SubArray[k]
            value += 100
            input.props.value = value //Uncaught TypeError: Cannot assign to read only property 'value' of object '#<Object>'
        }
    }
    F_ChangeB = () => {
        for (var k = 0, length = this.state.SubArray.length; k < length; k++) {
            let input = this.state.SubArray[k]
            input.props.value = 100 //Uncaught TypeError: Cannot assign to read only property 'value' of object '#<Object>'
        }
    }
}
class Subitem extends React.Component {
    render() {
        return (
            <input type="text" value={this.props.value} />
        );
    }
}

但是 TypeError:无法分配为只读对象“#”的属性“ value”

0 个答案:

没有答案