简体   繁体   English

如何在React中为每个组件设置样式?

[英]How to style each component in React?

I have following React code and it's CSS for a Scrolling functionality. 我有以下React代码,它是CSS的滚动功能。 When I am doing props.children.map it is giving me an error "TypeError: props.children.map is not a function". 当我在做props.children.map时,给我一个错误“ TypeError:props.children.map不是函数”。 It may be a simple mistake since I am still learning React.js. 这可能是一个简单的错误,因为我仍在学习React.js。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks! 谢谢!

**Scroll.js**

import React from 'react';
import './Scroll.css'

const Scroll = (props) => {

    return(
        <div class="slider">
        <div class="slide">

        {props.children.map((component) => 
        <div class="slide"> component </div>)
        }

        </div>
        </div>
    );
};
export default Scroll;

Scroll.css Scroll.css

.slider {
  width: 300px;
  height: 300px;
  display: flex;
  overflow-x: auto;
}
.slide {
  width: 300px;
  flex-shrink: 0;
  height: 100%;
}

The error you're getting makes sense because children is just one ReactNode and map will only work on an array of multiple values. 您得到的错误是有道理的,因为children只是一个ReactNodemap仅适用于多个值的数组。

You could do something like: 您可以执行以下操作:

import React from "react";
import "./Scroll.css";

const Scroll = props => {
  return (
    <div class="slider">
      <div class="slide">{props.children}</div>
    </div>
  );
};
export default Scroll;

And invoke Scroll like: 并像这样调用Scroll

const SomeParentComponent = () => {
  return (
    <Scroll>
      <div>
        <SomeChild />
        <SomeChild />
        <SomeChild />
      </div>
    </Scroll>
  );
};

You can trasforme you css in object like 您可以在对象中转换css

const styles = ({
input: {
    display: 'none',
},
pointerBorder: {
    borderWidth: '4px',
    borderStyle: 'dashed',
    borderColor: 'grey',
    paddingTop: '40px',
    paddingBottom: '40px',
},
iconUpload: {
    fontSize: '100px',
    cursor: 'pointer',
}

}); });

it is just one example. 这只是一个例子。 For to use, just call de object 要使用,只需调用de object

            <div className={styles.input}>

One more thing. 还有一件事。 try to comment the code 尝试注释代码

{props.children.map((component) => 
    <div class="slide"> component </div>)
    }

and run again, i think it is not a style probleam. 再次运行,我认为这不是样式问题。

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

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