简体   繁体   English

props.children是否会成为无状态组件?

[英]props.children in react cannot be a stateless component?

I'm trying to practice render props patter in react but I got error of 我试图在反应中练习渲染道具,但是我遇到了错误

this.props.children is not a function this.props.children不是函数

this is my code 这是我的代码

import React from 'react';
import { render } from 'react-dom';


const Box = ({color}) => (
  <div>
    this is box, with color of {color}
  </div>
);

class ColoredBox extends React.Component {
  state = { color: 'red' }
  getState() {
    return {
      color: this.state.color
    }
  }
  render() {
    return this.props.children(this.getState())
  }
}

render(<ColoredBox><Box /></ColoredBox>, document.getElementById('root'));

https://codesandbox.io/s/8z0xmk9ojl https://codesandbox.io/s/8z0xmk9ojl

As error says this.props.children is not a function or React Class(which is a function), instead it is an object created by invoking that function. 如错误所述,this.props.children不是函数或React Class(它是函数),而是通过调用该函数创建的对象。

You can use this to fix the problem 您可以使用它来解决问题

render() {
 return React.cloneElement(this.props.children, this.getState())
}

This will take the child, clone it using extra props. 这将带走孩子,并使用其他道具将其克隆。

Following the render props pattern, you need to have your children as a function, so you would indeed write 按照render props模式,您需要将孩子作为一个函数,因此您确实可以编写

import React from 'react';
import { render } from 'react-dom';


const Box = ({color}) => (
  <div>
    this is box, with color of {color}
  </div>
);

class ColoredBox extends React.Component {
  state = { color: 'red' }
  getState() {
    return {
      color: this.state.color
    }
  }
  render() {
    return this.props.children(this.getState())
  }
}

render(<ColoredBox>{(color) => <Box color={color}/>}</ColoredBox>, document.getElementById('root'));

Also to make it clear, a stateless functional component is not treated the same as a function when you render it like <Box/> 同样要明确的是,当您像<Box/>那样渲染无状态功能组件时,会将其视为与功能相同的组件

However you could use the above stateless functional component like 但是,您可以使用上面的无状态功能组件,例如

<ColoredBox>{Box}</ColoredBox>

and it would work 它会工作

Demo 演示版

You pass a React Object as props: 您将React对象作为道具传递:

(<ColoredBox><Box /></ColoredBox>)

Therefore it is not a function. 因此,它不是功能。

use: 使用:

render() {
    return this.props.children
}

OR, if you want you can pass a function as children prop (render-props): 或者,如果您愿意,可以将功能作为子道具(render-props)传递:

<ColoredBox>
  {state => <Box />}
</ColoredBox>

render() {
  return this.props.children(this.state)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM