簡體   English   中英

具有無 ID 圖像的可重用 React 復選框組件

[英]Reusable React checkbox component with image without ID

我正在嘗試為復選框制作可重用的 React 組件。

現在,我知道復選框的標准圖像替換是什么樣的,所以它在我的 React 項目中:

import React, { Component } from 'react';

class Checkbox extends Component {
  render() {
    return (
      <div className="checkbox">
        <input type="checkbox" name="thing" value="valuable" id="thing"/><label for="thing"></label> {this.props.text}
      </div>
    );
  }
}

export default Checkbox;

這是一般的CSS:

input[type=checkbox] {
  display:none;
}

input[type=checkbox] + label {
  background: url("checked.png") no-repeat;
  background-size: 100%;
  height: 20px;
  width: 20px;
  display: inline-block;
  padding: 0;
}
input[type=checkbox]:checked + label {
  background: url("unchecked.png") no-repeat;
  background-size: 100%;
  height: 20px;
  width: 20px;
  display: inline-block;
  padding: 0;
}

現在,因為這是 React,我希望能夠重用這個組件。 但是,我不能重復使用 ID。 我應該怎么做才能用圖像替換本機復選框? 沒有這種“標簽”方法,有沒有辦法做到這一點? 我不想使用隨機數作為 ID,或者類似的東西。

實例化組件時,將 id 作為 prop 傳遞給組件。

<Checkbox id="whatever" value={state.valueOrWhatever} text="Change The Value!" />

在組件(記for在JSX是htmlFor ):

<input type="checkbox" name={this.props.id} value={this.props.value} id={this.props.id} /> <label htmlFor={this.props.id}></label> {this.props.text}

我這樣做的方法通常是做這樣的事情:

<div className="checkbox">
   <label><input type="checkbox" value="valuable" /> <span>{this.props.text}</span></label>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM