相关疑难解决方法(0)

基于类的组件与功能组件有什么区别(Reactjs)

我是React的新手,我想清楚地知道要使用哪一个,当涉及到组件我会看到有两种类型.

功能组件:

import React from 'react'

const userInput = (props) => {
    return(
        <div>
            <input type='text' onChange={props.nameChanged} value={props.username}></input>
        </div>
    )
};

export default userInput;
Run Code Online (Sandbox Code Playgroud)

基于类的组件:

import React, { Component } from 'react';
import './App.css';
import UserOutput from './UserOutput/UserOutput';
import UserInput from './UserInput/UserInput';

class App extends Component {

  render() {
    return (
      <div className="App">
        <h3>Assignment Output :</h3>
        <ul>
          <li>
            <UserOutput 
            username={this.state.Usernames[0].username}>
            Welcome to React!
            </UserOutput>
            <UserInput 
            nameChanged={this.nameChangedHandler}>
            </UserInput>
          </li>
                      </ul>
      </div>
    );
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

我开始读到我们应该总是尝试使用Functional组件, …

javascript reactjs

9
推荐指数
1
解决办法
2285
查看次数

直接调用功能组件

无状态功能组件只是一个接收props和返回React元素的函数:

const Foo = props => <Bar />;
Run Code Online (Sandbox Code Playgroud)

这种方式<Foo {...props} />(即React.createElement(Foo, props))在父组件中可以省略,有利于Foo直接调用Foo(props),因此React.createElement可以消除微小的开销,但这不是必需的.

用props参数直接调用函数组件被认为是一种不好的做法,为什么?这样做有什么可能的影响?这会以负面的方式影响性能吗?

我的具体情况是,有一些组件是DOM元素的浅包装,因为这被第三方认为是个好主意:

function ThirdPartyThemedInput({style, ...props}) {
  return <input style={{color: 'red', ...style}} {...props} />;
}
Run Code Online (Sandbox Code Playgroud)

这是一个演示此案例的演示.

这是一种被广泛接受的做法,但它的问题在于无法ref从无状态函数中获取包装的DOM元素,因此该组件使用React.forwardRef:

function withRef(SFC) {
  return React.forwardRef((props, ref) => SFC({ref, ...props}));
  // this won't work
  // React.forwardRef((props, ref) => <SFC ref={ref} {...props } />);
}

const ThemedInput = withRef(ThirdPartyThemedInput);
Run Code Online (Sandbox Code Playgroud)

这样它可以用作:

<ThemedInput ref={inputRef} …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs

8
推荐指数
1
解决办法
486
查看次数

React - 偏好:函数组件与类组件

是否放弃了类组件?

我看到在几个库示例中,函数组件是优先考虑的。

尤其是 React 导航。

同样,带有 Hook 的 React 本身仅使它们可用于函数组件。

主要问题是:为什么功能组件如此重要?

reactjs react-native react-navigation

5
推荐指数
1
解决办法
5608
查看次数