首页 > 解决方案 > React:在子组件中改变 Ref 对象的实例

问题描述

class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.data = React.createRef()
  }

  componentDidMount() {
    this.data.current = []
  }

  render() {
    return <Child data={data} />
  }
}

const Child = ({ data }) => {

  const onDelete = (idx) => {
    data.splice(idx, 1)
  }
  return (
    <button onClick={(index) => onDelete(index)}>Delete</button>
  )
}

我需要这个 ref 是一个数组来解释一些复杂的原因,尽管代码正在完成这项工作,但我不确定ref在子组件中改变 prop 是否正确。我的问题是:如果我传递给子组件的道具不是父组件中的状态,那么可以对其进行变异吗?或者在裁判的情况下,它的工作方式不同吗?提前感谢您的帮助!

标签: reactjs

解决方案


推荐阅读