简体   繁体   中英

React stateless component not working

This is my code:

import React, { Component } from 'react'
import { BackButton } from 'components/button'

class LandingHeader extends Component {

    render() {

        const back = (props) => <BackButton forcedBackUrl={props.back.forcedBackUrl} />

        return (
             <div>
                 {back}
                 {this.props.children}
             </div>
         )
    }

}

export default LandingHeader

If i put the <BackButton> component directly it works but if I use a stateless component and return it inside this one it wont. What im missing?

Im following the official documentation ( https://facebook.github.io/react/docs/reusable-components.html ) and I can't see whats wrong. Thanks.

Looking at the facebook documentation that you provided they give the example of :

const HelloMessage = (props) => <div>Hello {props.name}</div>;
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);

and not just returning {HelloMessage}

therefore replace

{back}

with

<Back />

and you should be good to go

You've declared a ReactClass but you aren't rendering it - you have to turn it into a ReactElement :

const Back = (props) => <BackButton forcedBackUrl={props.forcedBackUrl} />

return (
  <div>
    <Back {...this.props.back} />
    {this.props.children}
  </div>
);

You need to inject the props into the component

import React, { Component } from 'react'
import { BackButton } from 'components/button'

    class LandingHeader extends Component {

        render() {

            const back = (props) => <BackButton forcedBackUrl={props.back.forcedBackUrl} />

            return (
                 <div>
                     {back(this.props)}
                     {this.props.children}
                 </div>
             )
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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