更改样式组件上的道具并更新外观

时间:2019-05-03 15:13:25

标签: reactjs styled-components react-proptypes

我对样式化组件非常陌生(而且我通常对React也不满意),我无法完全理解它们。我创建了一个基本示例,它是我想要实现的目标的抽象。当我单击该框时,我希望将属性from imutils.perspective import four_point_transform from imutils import paths import numpy as np import imutils import argparse import cv2 import random import math import matplotlib.pyplot as plt scaling_factorx = 0.8 scaling_factory = 0.8 cap = cv2.VideoCapture(0) fgbg = cv2.createBackgroundSubtractorMOG2() cap.set(3,640) cap.set(4,480) count = 0 height = [] while(1): ret, frame = cap.read() if frame is None: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 1, 100) lines = cv2.HoughLinesP(edges, rho = 1,theta = 2*np.pi/180,threshold = 10,minLineLength = 100,maxLineGap = 10); if lines is not None: for line in lines[0]: dot1 = (line[0],line[1]) dot2 = (line[2],line[3]) cv2.line(frame, dot1, dot2, (255,0,0), 3) length = line[1] - line[3] print(length) height.append(length) cv2.imshow("output", frame) frame = cv2.resize(frame, None, fx = scaling_factorx, fy = scaling_factory, interpolation = cv2.INTER_AREA) fgmask = fgbg.apply(frame) cv2.imshow('frame', fgmask) gray_vid = cv2.cvtColor(frame, cv2.IMREAD_GRAYSCALE) cv2.imshow('Original', frame) edged_frame = cv2.Canny(frame, 1, 100) cv2.imshow('Edges', edged_frame) if cv2.waitKey(1) & 0xFF ==ord('q'): break x = [] y = [] for i in range(len(height)): x.append(i) y.append(height[i]) cap.release() cv2.destroyAllWindows() print(x,y) plt.plot(x, y) plt.xlabel('x - axis') plt.ylabel('y - axis') plt.title('Height') plt.show() 更改为on,并希望根据true规则将<Box>的颜色更新为绿色。

我该如何实现?尤其是在箱子数量不确定的情况下?

组件

background-color

实施

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const Box = styled.a`  
    display: block;
    height: 100px;
    width: 100px;
    background-color: ${props => props.on ? 'green' : 'red' };
`;

Box.propTypes = {
    on: PropTypes.bool,
    onClick: PropTypes.func,
}

Box.defaultProps = {
    on: false,
    onClick: () => {},
}

export default Box;

2 个答案:

答案 0 :(得分:0)

您将在其父组件中处理状态。例如,您可以执行以下操作:

class Page extends Component {
  state = { on: false }

  handleClick = () => {
    this.setState(prevState => ({ on: !prevState.on }));
  }

  render() {
    return <Box on={this.state.on} onClick={this.handleClick} />
  }
}

或更简单地使用React挂钩:

const Page = () => {
  const [on, setOn] = useState(false);
  return <Box on={on} onClick={() => setOn(on => !on)} />;
};

这是一个示例,如果您想要10个盒子,该怎么办

(注意:如果您有很多盒子,像我一样在render方法中创建onClick处理程序可能会导致性能问题)

class Page extends Component {
  state = { boxes: Array(10).fill(false) }

  handleClick = (index) => {
    this.setState(prevState => ({
      boxes: [
        ...prevState.boxes.slice(0, index),
        !prevState.boxes[index],
        ...prevState.boxes.slice(index)
      ]
    }));
  }

  render() {
    return (
      <React.Fragment>
        {this.state.boxes.map((on, index) =>
          <Box on={on} onClick={() => this.handleClick(index)} />
        )}
      </React.Fragment>
    );
  }
}

答案 1 :(得分:0)

// App.js

import React from "react";
import ReactDOM from "react-dom";
import Test from "./Test";

class App extends React.Component {
  state = {
    on: false
  };
  handleChange = () => {
    this.setState(prevState => ({ on: !prevState.on }));
  };
  render() {
    return (
      <div className="App">
        <Test on={this.state.on} onClick={this.handleChange}>
          Hey
        </Test>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

// Test.js

import PropTypes from "prop-types";
import styled from "styled-components";

const Box = styled.a`
  display: block;
  height: 100px;
  width: 100px;
  background-color: ${props => (props.on ? "green" : "red")};
`;

Box.propTypes = {
  on: PropTypes.bool,
  onClick: PropTypes.func
};

Box.defaultProps = {
  on: false,
  onClick: () => {}
};

export default Box;