【问题标题】:Aligning button's text to the left左对齐按钮的文本
【发布时间】:2017-11-04 13:18:24
【问题描述】:

我有下一个代码:

<button onClick={this.openModal}>[{this.props.defaultValue}]</button>

获取的文本
[{this.props.defaultValue}]

始终居中。有没有办法让它向左对齐?

这是我目前正在尝试的:

const bstyle = { 
        textAlign:'left',
        color: 'white'
     };
    const {open} = this.state;
    return (
            <div>
            <button style={bstyle} onClick={this.onOpenModal}>[{this.props.defaultValue}]</button>

 ....

没有结果。 :-( 我可以看到按钮向左对齐。但它的文字要居中。

【问题讨论】:

    标签: css reactjs ecmascript-6


    【解决方案1】:

    您可以为此设置“文本对齐”

    <button onClick={this.openModal} style="text-align: left;">[{this.props.defaultValue}]</button>
    

    或者您可以定义 class 并将其设置为 CSS

    <button onClick={this.openModal} class="text-left">[{this.props.defaultValue}]</button>
    
    <style>
        .text-left{
            text-align: left;
        }
    </style>
    

    【讨论】:

    • 从我得到的第一个错误开始:未捕获的错误:style 道具需要从样式属性到值的映射,而不是字符串。例如,使用 JSX 时 style={{marginRight: spacing + 'em'}}。
    • 您可以使用style={{paddingLeft:'0px'}}style={{textAlign:'left'}} 或两者都使用
    【解决方案2】:

    样式需要object

    在 React 中,内联样式不指定为字符串。相反,他们 用一个对象指定,该对象的键是驼峰式版本的 样式名称,其值为样式的值,通常为 字符串。

    padding-left设置为0px

    这样写:

    <button onClick={this.openModal} style={{paddingLeft:'0px'}}>{this.props.defaultValue}</button>
    

    检查一下:

    var App = () => {
       return (
          <div>
             <button style={{paddingLeft:'0px'}}>Hello World</button>
          </div>
       )
    }
    
    ReactDOM.render(<App/>, document.getElementById('app'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id='app'/>

    【讨论】: