繁体   English   中英

React:如何根据另一个 JSX 元素更改样式属性?

[英]React: how to change the style property of one JSX element based on another?

我正在尝试用反应做一些造型。 我有一个结果页面,我希望我的结果卡(有点)伸展以填满每一行。 为此,我正在使用...

let body = {
  display: "flex",
  margin: "0% 10%",
  flexWrap: "wrap",
};

和...

let card = {
    fontSize: "90%", 
    flexBasis: "15rem",
    minWidth: "10rem",
    flexShrink: "1",
    flexGrow: "1",
}

我的问题是我还希望所有结果卡的大小相同。 通常,我会考虑为此使用 jQuery,但我使用的是 React,这有点尴尬。

所以,我要做的是通过回调 function 将第一个结果卡(子组件)的宽度信息传递回结果页面(父组件)。 然后,我打算使用道具将“maxWidth”属性传递给其他结果卡。 注意:这是可行的,因为我可以将宽度信息传递回父级,并且可以使用道具设置结果卡的样式。

问题是当我尝试将宽度信息分配给其他结果卡之一的道具时,它是未定义的。 我怀疑这是因为您无法在 JSX 元素呈现时更新 state 并从 state 获取信息......

关于如何实现我想要的任何想法? 关于如何以某种方式暂停渲染以更新 state 的任何想法?

一切顺利

父组件

import React from 'react';
import ReactDOM from 'react-dom';
import Card from './Card.js';

class Body extends React.Component {
constructor(props){
  super(props);
  this.state = {
  };
  this.cardWidth = function (width) {
    this.state.cardWidth = width;
    console.log(this.state.cardWidth);
  }.bind(this);
};
render() {
  return (
    <div className="body" style={body}>
      <Card cardWidth={this.cardWidth}/>
      <Card style={{maxWidth:`${this.state.cardWidth}`}}/>
      <Card style={{maxWidth:`${this.state.cardWidth}`}}/>
    </div>
  );
};
};

let body = {
  display: "flex",
  margin: "0% 10%",
  flexWrap: "wrap",
};

export default Body;

子组件

import React from 'react';
import ReactDOM from 'react-dom';

class Card extends React.Component {
constructor(props){
    super(props);
    this.state = {
    };
    this.cardref = React.createRef();
};
componentDidMount() {
    if (this.props.cardWidth) {
        this.props.cardWidth(this.cardref.current.offsetWidth);
    };
};
render() {
    return (
        <div className="card" style={(this.props.style)?(Object.assign({}, this.props.style, card)): card} ref={this.cardref}>
            <div className="card-body">
                <h5 className="card-title" style={{fontSize: "100%"}}>Card title</h5>
                <p className="card-text" style={pText}>Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                <a href="#" className="btn btn-primary" style={{fontSize: "80%"}}>Go somewhere</a>
            </div>
        </div>
    );
};
};

let card = {
    fontSize: "90%", 
    flexBasis: "15rem",
    minWidth: "10rem",
    // maxWidth: "15rem",
    flexShrink: "1",
    flexGrow: "1",
}

let pText = {
    display: "block",
    textOverflow: "ellipsis",
    overflow: "hidden",
    height: "4rem",
    fontSize: "80%"
};

export default Card;

原来我在 maxWidth 属性值之后错过了 px 。 现在我有一个问题,我需要它在视口调整大小事件上重新渲染。

期望的行为

要在给定空间内使所有卡片大小相同,可以使用flex-grow 例如,如果您在所有卡片上设置flex-grow: 1 ,那么它们将全部增长以均匀填充额外空间。 如果您寻找“flex-grow”标题,此页面上也有一个很好的图表。

暂无
暂无

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

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