Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

reactjs - How do I define methods in stateless components?

If I simply have:

const App = function() {
    return (
        <div>{this.renderList()}</div>
    )

}

How do I define the renderList method?

I can't do const renderList = function() {} (nor with var or let). I can't do renderList() {}.

What's the right syntax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am hesitant to give a solution to this because inline Stateless Functions are not supposed to have methods. if you want a method you should use a Class and theres nothing wrong with using a class. Its all based on what you need to do. Stateless Functions are designed to be a super light weight way to render something that doesn't need methods, or a state or even a this context (in terms of a class).

you should be doing it like this.

class App extends Component {
    constructor(){
        super();
        // note this is a Stateless Component because its a react class without a state defined.
    }
    renderList = () => {
        return <span>Something Here</span>;
    }
    render() {
        return <div>{this.renderList()}</div>
    }
}

a HACK way that I wouldn't recommend (but does solve your question in the way you want it to) would be like this.

const App = () => {
    let renderList = () => {
        return <span>Something Here</span>
    }
    return <div>{renderList()}</div>
}

The reason why its generally a bad practice is because you are creating a function and all the memory allocation needed every render cycle. Subsequently, the internal diffing optimizations that react provides is generally useless if you do this because a new function gives a different signature than the prior render cycle. If this had a lot of children, they would all be forced to re-render!

Edit - React Version 16.8.0 +

You can use Hooks to do this. I would recommend using memo to memoize the function, this way you aren't creating it in memory each render cycle.

const RenderList = React.memo(props => (
  <span>Something Here</span>
))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...