How to use function inside JSX

我只是一个虾纸丫 提交于 2020-01-01 19:55:13

问题


I am currently reading React offial website, where I came across this question. React official website states that we can use function code inside JSX. Hence, I tried following code, but it's not working.

class ABCD extends React.Component {

render() {
    return (
        <div>
            <p>
                {() => <div>Hello World </div>}
            </p>
        </div>
    );
}

}

I know, I know, some of you might say see example given on React website. I saw it, the example given on official website involves outside function. I just want to know that can we use function inside JSX independently.

See this link for extra info: https://reactjs.org/docs/jsx-in-depth.html


回答1:


As I feel what you are trying to do is wrong.

Object or functions are not parsable by JSX

If you just try

render() {
    return (
        <div>
            <p>
                {() => <div>Hello World </div>}
            </p>
        </div>
    );
}

You are trying to interpolate or return a function which is not acceptable as presentation node. It should be something which can be parsed by jsx. An object or a function cannot parse by JSX, they should be parsed by the Javascript engine.

What you can do is define your method and invoke that immediately so the function(iife function) returns something which could be parsed by JSX.

Something like

render() {
    return (
        <div>
            <p>
                {(() => {<div>Hello World </div>})()}
            </p>
        </div>
    );
}

Hope you get the point. Return something which can be parsable by JSX.




回答2:


Just call a function that returns JSX. For example:

class FooComp extends React.Component {
    someFunction() {
        return (<div>Hello World!</div>);
    }

    render() {
        return (
            <div>
                    <p>
                        {this.someFunction()}
                    </p>
            </div>
        );
    }
}



回答3:


You can try calling it as an inmediately invoked function

render() {
    return (
        <div>
            <p>
                {(() => <div>Hello World </div>)()}
            </p>
        </div>
    );
}



回答4:


Besides the immediately invoked function mentioned in other answers, the documentation mentions that it also possible to use a function as a child, which can be invoked as props.children(...args).

The key thing is that the component must ultimately return something renderable:

Children passed to a custom component can be anything, as long as that component transforms them into something React can understand before rendering. This usage is not common, but it works if you want to stretch what JSX is capable of.



来源:https://stackoverflow.com/questions/48443081/how-to-use-function-inside-jsx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!