【问题标题】:Passing a prop to a child created after component mounts将道具传递给组件安装后创建的孩子
【发布时间】:2017-12-22 19:58:06
【问题描述】:

我有一个组件是<canvas> 的容器。我还有其他将画布上下文作为道具的组件,可用于以各种方式对其进行操作;像这样:

class App extends React.Component {
  ctx: CanvasRenderingContext2D;
  canvas: HTMLCanvasElement;

  componentDidMount() {
    this.ctx = this.canvas.getContext('2d') as CanvasRenderingContext2D;
    this.forceUpdate();
  }

  render() {
    const circle = this.ctx ? <Circle ctx={this.ctx} /> : '';
    return (
      <canvas ref={ref => (this.canvas = ref as HTMLCanvasElement)}>
        {circle}
      </canvas>
    );
  }
}

const Circle = ({ ctx }: { ctx: CanvasRenderingContext2D }) => {
  ctx.arc(10, 10, 10, 0, 6);
  ctx.stroke();
  return null;
};

这按预期工作并画了一个圆圈,但我不确定这是最好的方法。我有几个问题:

  • 我不确定forceUpdate 电话。
  • 如果我不对ctx 进行条件检查,Circle 首次渲染时将未定义。

我最初使用的是componentWillMount,但问题是没有设置ref,所以this.canvas是未定义的。

是否有适当的方法将 props 传递给依赖于父级中的 refs 的子组件?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    我认为一种方法如下:

    class App extends React.Component {
      ctx: CanvasRenderingContext2D;
      canvas: HTMLCanvasElement;
    
      constructor(props){
         super(props);
         this.state={ ctx:null }
      }
    
      componentDidMount() {
        this.setState({ctx:this.canvas.getContext('2d') as CanvasRenderingContext2D})
      }
    
      render() {
        const circle = this.state.ctx? <Circle ctx={this.state.ctx} /> : '';
        return (
          <canvas ref={ref => (this.canvas = ref as HTMLCanvasElement)}>
            {circle}
          </canvas>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 2017-06-03
      • 2018-04-09
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2018-07-07
      • 2019-10-16
      相关资源
      最近更新 更多