React:如何通过另一个组件访问和更改 state/atributes?

React: How to access and change state/atributes via another component?

我想更改 ComponentA(当前索引)的 ComponentB 属性值。

我的方法是调用下层组件函数来改变它们的state/values

import React from 'react'

class TaskComp extends React.Component{
 
    constructor(props){
        super(props);
        this.state = {
            name: "",
            starTime: 0,
            endTime: 0
        }
        this.changeState = this.changeState.bind(this)
        // this.changeState = this.changeName.bind(this)
    }
    
    changeState(newName, newStart, newEnd){
        // this.setState()
            this.state.name = newName
            this.state.starTime = newStart
            this.state.endTime = newEnd
        }
         
}

function changeName(newName){
    this.state.name = newName
}

function componentDidMount() {
    // this.setState(this.state)
}



function renderTask(){
    let task = new TaskComp()
    return <div> 
    
    <p>{Object.keys(task.state).map((key) => <div key={key}>{key} {task.state[key]}</div>)}</p>
    </div>
}


export default renderTask


例如:创建一个名为“Paul”的任务,数据来自其他地方,例如 TextField、DB...

当我尝试这样做时,它说 changeName 或 changeState 不是函数。我假设是因为 Tasks 返回的是 Div 而不是实际的 class/object/data。我无法通过道具访问(假设它是只读的)。

1.WhatJS/React概念涉及此问题(研究)

2.How实现解决方案?

谢谢安迪的帮助。我改为 return 整个 class 并以这个结束。

高级组件

task.setState("Moe", 12,30)
<p>{task.render()}</p>

较低的组件

import React from 'react'

class Task extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            name: "",
            starTime: 0,
            endTime: 0
        }
        // this.changeState = this.changeState.bind(this)
        // this.changeState = this.changeName.bind(this)
    }

    setState(newName, newStart, newEnd) {
        // this.setState()
        this.state.name = newName
        this.state.starTime = newStart
        this.state.endTime = newEnd
    }

    componentDidMount() {
    }

    render(){
        return <div>
            {Object.keys(this.state).map((key) => <div key={key}>{key} {this.state[key]}</div>)}
        </div>
    }
} 

export default Task