且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在无状态组件中定义方法?

更新时间:2022-12-24 07:45:04

我很犹豫要不要给出解决方案,因为内联 Stateless Functions 不应该有方法.如果你想要一个方法,你应该使用 Class 并且使用类没有任何问题.这一切都基于您需要做什么.Stateless Functions 被设计成一种超轻量级的方式来渲染不需要方法、状态甚至 this 上下文(就类而言)的东西.

应该这样做.

class App 扩展组件 {构造函数(){极好的();//注意这是一个无状态组件,因为它是一个没有定义状态的反应类.}renderList = () =>{return <span>Something Here</span>;}使成为() {返回 <div>{this.renderList()}</div>}}

我不推荐HACK方式(但确实以您希望的方式解决您的问题)将是这样的.

const App = () =>{让 renderList = () =>{return <span>Something Here</span>}返回 
{renderList()}

}

为什么它通常是不好的做法是因为您正在创建一个函数并且每个渲染周期都需要所有内存分配.随后,如果您这样做,react 提供的内部差异优化通常是无用的,因为新函数提供了与先前渲染周期不同的签名.如果这有很多孩子,他们都会***重新渲染!

编辑 - React 版本 16.8.0 +

你可以使用 Hooks 来做到这一点.我建议使用 memo 来记忆函数,这样你就不会在每个渲染周期在内存中创建它.

const RenderList = React.memo(props => (<span>这里有东西</span>))

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?

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>
))