【问题标题】:React: How to access and change state/atributes via another component?React:如何通过另一个组件访问和更改状态/属性?
【发布时间】:2022-01-16 23:01:00
【问题描述】:

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

我的方法是调用较低的组件函数来更改它们的状态/值

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 而不是实际的类/对象/数据。我无法通过道具访问(假设它是只读的)。

1.什么JS/React概念涉及到这个问题(研究)

2.如何实现解决方案?

【问题讨论】:

  • 你的代码有很多问题,使用类组件,确保你有一个 render 函数,这基本上就是你所拥有的 renderTask 但你有它在您的组件之外。您也不能在组件类范围之外的函数中访问state。我建议您阅读reactjs.org/docs/react-component.htmlreactjs.org/docs/components-and-props.html 以了解如何编写组件和使用道具在它们之间传递数据和处理程序的一些基本知识

标签: javascript reactjs react-hooks react-props react-component


【解决方案1】:

感谢安迪的帮助。我改变了返回整个班级并结束了这个。

高级组件

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多