【问题标题】:apply class based on props on render基于 props 在渲染上应用类
【发布时间】:2018-10-02 01:44:19
【问题描述】:

所以,使用 react,我正在检查我的点击道具,并根据这些道具应用或不应用一个类到我的按钮。问题是我需要在渲染时进行验证。我正在考虑一种在渲染上运行的方法(selectedThumbnails ?),但我不太确定如何处理验证。

这是我的组件:

class Thumbnail extends Component {
    constructor(props){
        super(props);
    }

    selectedThumbnails = () => {
        console.log(this.props.selectedThumbnails()
    }

    render() {

        return (

            this.selectedThumbnails(),

            <div onClick={() => this.props.escolheTextura(this.props.textures)}
                 className={this.props.thumbnailsAtives.some(thumbnail => thumbnail === this.props.textures) ? "button is-primary thumbnail" : "button thumbnail"}>
                <Tooltip title={this.props.textureName}>
                <span>
                    <figure className={"image is-32x32"}>
                        <img src={this.props.textures.urlImage}/>
                    </figure>
                </span>
                </Tooltip>
            </div>
        )
    }
};

如果数组 thumbnailsAtivas 中有一些按钮(如“this.props.textures”中的按钮),我的 onclick 会将“按钮是主缩略图”类应用于按钮/按钮。我还需要在渲染时检查这一点,比如在 onLoad 左右,但我不知道如何使用 onLoad 方法应用一个类。

【问题讨论】:

    标签: javascript reactjs classname


    【解决方案1】:
    class Thumbnail extends Component {
        constructor(props){
            super(props);
            this.state={
              selectedThumbnail:null
            }
        }
    
        thumblick = (thumb) => {
         this.setState({selectedThumbnail:thumb })
        }
    
    
        render() {
    
            return (
    
    
                <div onClick={() => this.thumblick(this.props.textures) }
                     className={this.state.selectedThumbnail === this.props.textures) ? "button is-primary thumbnail" : "button thumbnail"}>
                    <Tooltip title={this.props.textureName}>
                    <span>
                        <figure className={"image is-32x32"}>
                            <img src={this.props.textures.urlImage}/>
                        </figure>
                    </span>
                    </Tooltip>
                </div>
            )
        }
       };
    

    首先定义一个空的状态变量来保存选中的图像。 单击时应将状态设置为当前选定的缩略图。更改状态会导致重新渲染,这次它将通过每个缩略图与存储在状态中的选定缩略图进行比较。 到时候它将类应用到按钮

    【讨论】:

    • 感谢您的回答,但这并不能解决我的问题。当应用程序运行时,我已经选择了一组缩略图,我只需要基于它们应用类,到目前为止,我从你的帮助中了解到,我没有选择任何缩略图。另外,我需要这个来第一次在渲染而不是点击时检查道具
    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2018-07-01
    • 2021-11-10
    • 2021-07-04
    相关资源
    最近更新 更多