动态更改自定义控件样式

时间:2017-02-21 18:37:13

标签: reactjs

动态更改自定义控件样式

我正在尝试使用react在每个自定义字段周围放置红色边框。数组this.address = address; this.sqft = sqft; 包含要检查的所有控件。 我想检查每个必需的控件,如果未设置其值,请更改其this.state.Fields属性。由于属性无法更改,我尝试使用style,但问题是我需要为每个控件单独设置一个vriable:

state

我想知道是否有更优雅的方式来做到这一点?这是我的代码:

<Control ref="controlLabel" name="controlLabel" type="1" onComponentMounted={this.register} label="Control Label:" required="1" value={this.state.controlLabel} localChange={this.handleControlLabelChange} inputStyle={{border: this.state.errControlLabelStyle}} />

1 个答案:

答案 0 :(得分:0)

您可以在Control本身内添加验证逻辑。

&#13;
&#13;
var Control = React.createClass({
	isValid: function() {
  	if (!this.props.required) {
    	return true;
    }
  	return this.props.value !== '' && this.props.value !== undefined;
  },

  render: function() {
  	let value = this.props.value;
    return <div className={this.isValid() ? 'item valid' : 'item invalid'}>{value}</div>;
  }
});

var App = React.createClass({
  render: function() {
    return (
    	<div className="container">
      	{[
        {
          required: true,
          value: ''
        },
        {
          required: true,
          value: 'abc'
        },
        {
          required: false,
          value: ''
        }
        ].map((v, i) => <Control key={i} required={v.required} value={v.value} />)}
      </div>
    );
  }
});

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
&#13;
.valid {
   border-color:  green;
}

.invalid {
  border-color: red;
 }
 
 .item {
   width:  200px;
   height: 50px;
   border-width: 1px;
   border-style: solid;
   margin: 1px;
   display: flex;
 }
 
 .container {
   display: flex;
 }
&#13;
<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="container">
    <!-- This element's contents will be replaced with your component. -->
</div>
&#13;
&#13;
&#13;