Direct call of a functional component

前端 未结 2 708
忘掉有多难
忘掉有多难 2020-12-02 00:28

Stateless functional component is just a function that receives props and returns React element:

const Foo = props => ;
<         


        
2条回答
  •  心在旅途
    2020-12-02 00:46

    I don't think there's anything wrong with calling Stateless Functional Component directly. As you said it's even one tiny overhead eliminated. As to the possible implications, it would be bold to say that there are none implications and there will be none implications in the future because this is a really rare way of using SFC's. But everything points to conclusion that there shouldn't be any implications (it's just one function call less).

    Anyway, below I'd like to present another way of doing this using findDOMNode instead of refs:

    I've created Focus component that is really convenient to use but needs to be initialized first (since we need a way to trigger focus outside props since a component may be rerendered with the same props):

    // focus.js
    import React from "react";
    import { findDOMNode } from "react-dom";
    
    export default function createFocus() {
      class Focus extends React.Component {
        componentDidMount() {
          Focus.now = () => {
            findDOMNode(this).focus();
          }
        }
        render() {
          return this.props.children;
        }
      }
    
      return Focus;
    }

    // index.js
    import React, { Component } from 'react';
    import { render } from 'react-dom';
    import createFocus from './focus';
    
    const Focus = createFocus();
    
    import { ThirdPartyThemedInput } from './third-party-lib';
    
    function App() {
      return (
        
    ); } render(, document.getElementById('root'));

    live at: https://stackblitz.com/edit/react-bpqicw

提交回复
热议问题