如何使用反应材质UI覆盖TextField组件的宽度?

时间:2016-01-29 20:04:55

标签: javascript reactjs reactive-programming material-ui

我试图减少该组件的宽度:

https://github.com/callemall/material-ui/blob/master/src/TextField/TextField.jsx

这是渲染方法:

  render() {

    return (
      <div>
          <div>
            <form onSubmit={this.handleSubmit}>
                <TextField
                  hintText="Email"
                  ref="email"
                /><br/>
                <TextField
                  hintText="Password"
                  type="password"
                  ref="password"
                /><br/>
              <button className="btn btn-success" onClick={this.loginCommand}><i className="fa fa-sign-in"/>{' '}Log In</button>
            </form>
          </div>
      }
      </div>
    );
  }
}

Thx!

enter image description here

4 个答案:

答案 0 :(得分:13)

您可以在元素上指定内联样式,如下所示

  <TextField
        hintText="Email"
        ref="email"
        style = {{width: 100}} //assign the width as your requirement
   />

或者你可以这样做。

使用css属性声明styles变量。

var styles = StyleSheet.create({
    textFld: { width: 100, height: 40}   //assign the width as your requirement
});

将其分配到style代码中的render

<TextField
              hintText="Email"
              ref="email"
              style = {styles.textFld}
            />

尝试让我知道它是否适合你。我也是新的反应js。

为了清楚起见,您可以在SO上参考文档和其他类似问题。 http://facebook.github.io/react-native/docs/style.html#content

http://facebook.github.io/react-native/

http://facebook.github.io/react-native/docs/flexbox.html#content

React.js inline style best practices

答案 1 :(得分:13)

您还可以将fullWidth property与React Material UI一起使用。

<TextField
      id="full-width-text-field"
      label="Label"
      placeholder="Placeholder"
      helperText="Full width!"
      margin="normal"
      fullWidth
/>

答案 2 :(得分:2)

来自doc

  

样式 - &gt;对象 - &gt;覆盖根元素的内联样式。

     

inputStyle - &gt;对象 - &gt;覆盖TextField输入元素的内联样式。

     

所以你可以这样做:

 <TextField
     hintText=".."
     ref=".."
     style ={{width: '100%'}}
     inputStyle ={{width: '100%'}}
 />

也许还可以通过为组件提供id或className,并使用css进行定位(添加!important):

 <TextField
     id="myId"
     className="myClass"
 />

 -----

 .myId{
      width: 100% important!;
  }

答案 3 :(得分:0)

如果您想将TextField的宽度扩展为父母的宽度(width: 100%):

<TextField label="Full width" fullWidth />

如果要将TextField的宽度设置为确切的值:

<Box width={350}>
  <TextField label="width: 350px" fullWidth />
</Box>

如果您不想添加包装器组件,也可以直接设置TextField的样式。

const useStyles = makeStyles({
  root: {
    width: 350
  }
});

function App() {
  const classes = useStyles();
  return <TextField label="width: 350px" className={classes.root} />;
}

我建议您不要使用其他答案中建议的内联样式,因为内联样式更难覆盖。默认情况下,您应该使用Material-UI styles,因为它更灵活并且可以更好地与Material-UI组件集成。例如,您可以cherry-pick子组件以在较大的组件中进行覆盖,或者对psuedo类和元素进行样式设置,而内联样式无法做到这一点。

实时演示

Edit 35093107/how-to-override-the-width-of-a-textfield-component-with-react-material-ui

相关问题