【问题标题】:Cannot change the font size of <h1> within a component of react无法在反应组件中更改 <h1> 的字体大小
【发布时间】:2020-11-16 10:40:30
【问题描述】:
class App extends Component {

    constructor() {
        super()
        this.state = {   //state is what decribes our app
            robot: robot,
            searchfield: ''
        }
    } 

    onSearchChange = (event) =>  {
        this.setState({ searchfield: event.target.value })       
        console.log(this.state.robot);
    }  

    render() {
        const filteredRobots = this.state.robot.filter( robot => {
            return robot.name.toLowerCase().includes(this.state.searchfield.toLowerCase()); 
            })
        return(
        <div className='tc'>
            <h1>ROBOFRIENDS</h1>
            <SearchBox searchChange={ this.onSearchChange } />
            <CardList robot = { filteredRobots }/>  
        </div>
        );
    }
}

我正在尝试放大ROBOFRIENDS的字体大小,我尝试创建另一个用于编辑h1的css文件并尝试过

<h1 className="style:{fontSize=3em}">ROBOFRIENDS</h1>

但它们都不起作用。但是,当我尝试使用相同的方法更改字体颜色和背景颜色时,它们起作用了! 找人可以帮我解决这个问题。

【问题讨论】:

    标签: reactjs npm components font-size


    【解决方案1】:

    您不能使用 className 属性添加样式。你有两个选择:

    • 向元素添加className 并在css 中设置该className 的样式。
    • 或像这样添加style属性:style={{ fontSize: '3em' }}

    【讨论】:

      【解决方案2】:

      我更喜欢第二个:

      style={{ fontSize: '3em' }}
      

      因为这样你可以将变量传递给这个。

      但我最喜欢的方式是使用样式组件。 https://styled-components.com/

      检查一下,这是在 react.js 中设置样式并重用样式的一种非常干净的方式。

      【讨论】:

        【解决方案3】:

        有多种方法。我建议安装“样式组件”。 我在下面提供了一个如何使用它的示例:-

        import styled from 'styled-components';
        
        export const StyledHeading = styled.h1`
            font-size: 3em;
        `;
        
        
        class App extends Component {
        
            constructor() {
                super()
                this.state = {
                    robot: robot,
                    searchfield: ''
                }
            } 
        
            onSearchChange = (event) =>  {
                this.setState({ searchfield: event.target.value })       
                console.log(this.state.robot);
            }  
        
            render() {
                const filteredRobots = this.state.robot.filter( robot => {
                    return robot.name.toLowerCase().includes(this.state.searchfield.toLowerCase()); 
                    })
                return(
                <div className='tc'>
                    <StyledHeading>ROBOFRIENDS</StyledHeading>
                    <SearchBox searchChange={ this.onSearchChange } />
                    <CardList robot = { filteredRobots }/>  
                </div>
                );
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-08-15
          • 1970-01-01
          • 1970-01-01
          • 2018-09-27
          • 2011-01-20
          • 2021-08-25
          • 2021-03-17
          相关资源
          最近更新 更多