【发布时间】: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.html 和reactjs.org/docs/components-and-props.html 以了解如何编写组件和使用道具在它们之间传递数据和处理程序的一些基本知识
标签: javascript reactjs react-hooks react-props react-component