【问题标题】:i'm have problem compose between class compenent and stateless function component?我在类组件和无状态功能组件之间有问题吗?
【发布时间】:2020-08-25 23:07:48
【问题描述】:

app.js

import React from 'react';
import Header from './Header';
class App extends React.Component{
  render(){
    return(
      <Header />
    )
  }
}

export default App;

Header.js

import React from 'react'
const colorText = (props) => {
     const styles = {
         fontFamily : `${props.color}`
     }
}
class Header extends React.Component{
  constructor(props){
      super(props);
  }
  render(){
      return(
          <header >
             <colorText style = {styles}/>
              <p color = 'red'>Fo Fine!</p>
              <p color = 'green'>By Khoa-VoDuc</p>
              <p color = 'blue'>Great For QuilTing & Sewing</p>
          </header>
      )
      } 
    }
export default Header;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';


ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

错误

错误:'styles' 未定义 no-undef 。

我无法在类 Header 的渲染方法中访问 c​​olorText 函数。我想在屏幕上显示标签 p 中的这些文本,上面有三种颜色。

【问题讨论】:

    标签: javascript css reactjs components web-component


    【解决方案1】:

    styles 实际上并没有在Header.js 中定义。如果要在该文件上使用colorText 函数中定义的style,则必须先调用它:

    import React from 'react';
    
    const colorText = (color = 'inherit') => {
      const styles = {
        color,
        fontFamily: 'monospace',
      };
    
      // This `return` here is missing:
      return styles; 
    };
    
    class Header extends React.Component {
      constructor(props) {
        super(props);
      }
    
      render() {
        return(
          <header>
             { /*
               `colorText` return an object with a `color` prop, so you would
               assign that to the `style` attribute of some HTML element, not
               call it as a component as you were doing before.
    
               So this doesn't make sense because 1) `colorText` is not a
               component and 2) where have you defined this `styles` variable?:
    
               <colorText style={ styles } />
    
               Instead, use it like this:
             */ }
    
             <p style={ colorText('red') }>Fo Fine!</p>
             <p style={ colorText('green') }>By Khoa-VoDuc</p>
             <p style={ colorText('blue') }>Great For QuilTing & Sewing</p>
          </header>
        );
      }
    }
    
    export default Header;
    

    【讨论】:

    • @mplungjan 我已经更新它以解决其他问题。
    • 我仍然遇到问题:'props' 没有在 中定义为 no-undef。
    • @KhoaVõĐức colorText 不是 React 组件,它只是返回一个像 { color: 'red' } 这样的对象。检查它是如何在下面的&lt;p&gt; 元素中使用的。
    猜你喜欢
    • 2018-09-29
    • 2022-01-04
    • 1970-01-01
    • 2021-05-13
    • 2017-10-23
    • 2019-03-19
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多