简体   繁体   English

从ReactJS的组件状态传递样式

[英]Passing Style From Component State in ReactJS

I have the following component: 我有以下组成部分:

import React from "react";
import { connect } from "react-redux";

class Filter extends React.Component {
  state = {
    value: ''
  };

  handleChange = (e) => {
    let value = e.target.value;
    if(value){
      document.getElementById("clear").style["display"] = "none";
      document.getElementById("fetch").style["display"] = "none";

    } else {
      document.getElementById("clear").style["display"] = "inline-block";
      document.getElementById("fetch").style["display"] = "inline-block";
    }
    this.setState({ value });
    this.props.handleFilter({ value });
  }

  render(){
  let content = this.props.items > 0 ? (
      <div
        className="filter"
        >
        <input
          id="search-input"
          type="text"
          placeholder="Search..."
          value={this.state.value}
          onChange={this.handleChange}
        />
      </div>
    ) : <div></div>
    return content;
  }
}

const mapStateToProps = (state,props) => ({
  items: state.settings.length
});

module.exports = connect(mapStateToProps, null)(Filter);

Is there a way I can more gracefully pass props to the clear and fetch components? 有没有办法我可以更优雅地将道具传递给clear和fetch组件? I'm trying to style them based on interactions with my search input (basically, I'd like to be able to style them whenever my search value is at ""). 我正在尝试根据与搜索输入的交互来对它们进行样式设置(基本上,只要我的搜索值位于“”,我都希望能够对其进行样式设置)。 How do I send down styles as a prop based on the state of my current component? 如何根据当前组件的状态发送样式作为道具?

If you use a library called styled-components, you can easily do this like in this example: https://www.styled-components.com/docs/basics#passed-props . 如果您使用一个名为styled-components的库,则可以像下面的示例一样轻松地执行此操作: https : //www.styled-components.com/docs/basics#passed-props The idea with that lib is that you wrap your basic HTML components, like <input> to <Input> , then use the new <Input> component in your render() method. 该lib的想法是,将基本的HTML组件(如<input>封装为<Input> ,然后在render()方法中使用新的<Input>组件。 The new component will be controlled by passing values from your state as a prop. 新组件将通过传递状态值作为道具来控制。

Please react-jss that is exactly what you are searching for: please find the sample below: 请为您搜索的正是React-jss:请找到以下示例:

 import React, { Component } from 'react' import injectSheet from 'react-jss' import classNames from 'classnames' class someComponent extends Component { handleClose = () => {} render() { const { classes, } = this.props return ( < div className = { classes.resize } > < /div> ) } } const styles = { container: { width: '100%', height: '100rem' borderBottom: '10px' } } export default injectSheet(styles)(someComponent) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM