简体   繁体   English

React Prop渲染为对象 - 不明白为什么

[英]React Prop rendering as object - don't understand why

I'm new to React, and I just can't figure this out... 我是React的新手,我只是想不出来......

I'm trying to pass my state to a prop in the parent component, and then render that state in a child component. 我试图将我的状态传递给父组件中的prop,然后在子组件中呈现该状态。 Like so: 像这样:

Parent Component 父组件

class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         text: 'hello'
      }
   }
   render() {
      return (
         <div className="App">
            <MessageList textProp={this.state.text}/>
         </div>
      );
   }
}

Child Component 子组件

const MessageList = textProp => {
   return (
   <div className='MessageList'>
      {textProp}
   </div>
   )
}

React won't render properly, claiming it is an object that is trying to be rendered. React将无法正确呈现,声称它是一个试图呈现的对象。

I can access the property by using {textProp.textProp} , why is it rendering an object which contains a property of the same name? 我可以使用{textProp.textProp}访问该属性,为什么它呈现包含同名属性的对象?

I'm sure this is very simple but I could do with an explanation! 我确信这很简单,但我可以解释一下!

Thanks in advance. 提前致谢。

Components' props are an object, just as their state is an object. 组件的道具是一个对象,就像它们的状态是一个对象一样。 Therefore you want something more like: 所以你想要更像的东西:

const MessageList = props => {
   return (
   <div className='MessageList'>
      {props.textProp}
   </div>
   )
}

or, using destructuring: 或者,使用解构:

const MessageList = ({ textProp }) => {
   return (
   <div className='MessageList'>
      {textProp}
   </div>
   )
}

When you declare stateless component you need to specify the arguments you want it to receive it can be (props) or ({ specific }) in your case: 当您声明无状态组件时,您需要指定您希望它接收的参数,它可以是(props)({ specific })在您的情况下:

const MessageList = ({ textProp }) => (
 <div className='MessageList'>
      {textProp}
   </div>
);

Note how i do => () that will return the markup, you don't have do to { return () } just a tip to run things better :) 注意我怎么做=> ()将返回标记,你没有做{ return () }只是一个提示更好地运行:)

The textProp in MessageList is a collection of props form the parent. MessageListtextProp是父组合的props集合。 In your case the collection will have only textProp. 在您的情况下,集合将只有textProp. To make this work you need to do the following. 要完成这项工作,您需要执行以下操作。

const MessageList = ( {textProp} ) => {
   return (
   <div className='MessageList'>
      {textProp}
   </div>
   )
}

or 要么

const MessageList = (textProp) => {
   return (
   <div className='MessageList'>
      {textProp.textProp}
   </div>
   )
}

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

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