我在类组件和无状态函数组件之间有问题吗?

问题描述 投票:0回答:1

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

错误

错误:“样式”未定义为no-undef。

我无法在Header类的render方法中访问colorText函数。我想在屏幕上显示上面三种颜色的标签p中的这些文本。

javascript css reactjs components web-component
1个回答
1
投票

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

import React from 'react';

const colorText = (color = 'inherit') => {
    const styles = {
        fontFamily : `${ color }`
    };

    // This `return` here is missing:
    return styles; 
};

class Header extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return(
            <header>
                <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;
© www.soinside.com 2019 - 2024. All rights reserved.