在React项目中找到一个组件

时间:2018-12-09 13:53:08

标签: reactjs

我在React应用程序中编写了一个注销按钮组件,希望将其放置在屏幕的右上角。

render() {
   <LogoutButtonComponent height: , backgroudColor: />
}

不允许我为高度等分配任何值。

这是注销组件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class LogOutButton extends Component {
  static contextTypes = {
    store: PropTypes.object.isRequired,
  };

  handleClick = () => {
    this.props.onLogout();
  };

  render() {
    return <button type="button" onClick={this.handleClick}>Logout</button>;
  }
}

我应该通过找到它吗?

2 个答案:

答案 0 :(得分:0)

要添加内联样式,应将style对象定义为prop,然后将其传递值,例如提到的doniyor2109。但是,使用它有一些注意事项。

style={{ height: 100, height: '100px', height: '100%', minHeight: '100px'}}

  • 并非每个值都应作为整数传递,某些值需要作为字符串传递
  • 并非每个css属性都会像您期望的那样传递,css min-height实际上以minHeight的形式传递,因此请使用小写的驼峰样式替换所有连字符
  • 内联样式难以管理。我建议您至少在组件外部创建一个对象,并将其传递为:

const DivStyle = { minHeight: '100px' }

然后:

<LogoutButtonComponent style={DivStyle} />

  • 如果要在其他地方DivStyle,可以在export前面加上import {DivStyle} from './somefile'

  • 我建议您签出styled-components之类的库,因为它使样式设置变得更加容易!

  • 我建议您查看this article,其中概述了您的选择

答案 1 :(得分:0)

您并不是真的那样向您的组件添加样式。最好在实际组件的源代码中添加这些样式。那么,您希望它如何显示呢?我将提供一种模板,您可以将其更改为所需的模板。

转到“注销按钮组件”的来源。在渲染方法的返回中,尝试添加一个div调用它的容器。然后将css文件中的样式添加到该div中,或者如果您使用的是react-bootstrapreactstrap@material/ui/core,则可以根据其文档调整样式。

您可以将css添加到className .container,使其以您想要的方式显示。

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class LogOutButton extends Component {
  static contextTypes = {
    store: PropTypes.object.isRequired,
  };

  handleClick = () => {
    this.props.onLogout();
  };

  render() {
    return ( 
      <div className="container">
         {* notice the className here *}
         <button type="button" onClick={this.handleClick}>Logout</button>
     </div>
    )
  }
}

希望这会有所帮助。