【问题标题】:Toggle Class Map On Component切换组件上的类映射
【发布时间】:2018-05-22 17:23:13
【问题描述】:

如何通过组件中的“isSelected”单击事件在容器的状态中切换“isActive”?

请查看在我的容器中导入的“列出帐户”组件。我通过道具传递帐户数据。

当我遍历每个帐户时,我想检查“isActive”是真是假。

我假设这将决定何时呈现类。

是否可以让地图函数中的“项目”在我的“isSelected”函数中监听状态并更新状态?

解决此问题的最佳方法是什么?

这是我的容器代码:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import './index.css'; // styles from

import ProfileHeader from '../../../components/ProfileHeader';
import ListAccounts from '../../../components/ListAccounts';

import { fetchingPageData } from '../../../actions';


class WhosWatching extends Component {
  state = {
    accounts: [
      {
        isActive: false,
        isChild: false,
        name: 'Olivia',
        avatar: '/images/avatars/profile-img-03.png'
      },
      {
        isActive: false,
        isChild: false,
        name: 'Fred',
        avatar: '/images/avatars/profile-img-01.png'
      },
      {
        isActive: false,
        isChild: true,
        name: 'Dirk',
        avatar: '/images/avatars/profile-img-02.png'
      },
    ]
  }

  render() {
    const listAccounts = this.state.accounts;
    return (
      <div className="whos-watching-wrap container">
          <ProfileHeader />
          <h1>Who's Watching?</h1>
          <span>Select an account or add a new profile</span>
          <ListAccounts accounts={listAccounts} />
          <div className="whos-watching-cta">
            <button>Add Profile</button>
          </div>
      </div>
    );
  }
};

这是我列出帐户的组件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import KidsIcon from '../../assets/svg/icons/kids.svg';

import './index.css';

export default class ListAccounts extends Component { 
    isSelected() {
    }

    render() {
        const { accounts } = this.props;
        return (
            <div className="list-accounts-wrap">
                {accounts.map((item, i) => {
                    return <div className="list-accounts-item is-selected" onClick={() => this.isSelected()} key={i}>
                        <img src={item.avatar} />
                        <div className="account-details-wrap">
                            <span className="account-name">{item.name}</span>
                            {item.isChild == true ? <KidsIcon /> : null }
                        </div>
                    </div>
                })}             
            </div>
        )
    }

}

【问题讨论】:

  • 你想在切换命中时与主状态(WhosWatching)同步吗?
  • @NishantDixit 是的,因为这些数据需要存储在本地会话中,所以我需要在用户旅程中从状态中获取它。我假设?
  • @Flith 检查我的答案,我认为它符合您的要求。

标签: javascript reactjs


【解决方案1】:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import './index.css'; // styles from

import ProfileHeader from '../../../components/ProfileHeader';
import ListAccounts from '../../../components/ListAccounts';

import { fetchingPageData } from '../../../actions';


class WhosWatching extends Component {
  state = {
    accounts: [
      {
        isActive: false,
        isChild: false,
        name: 'Olivia',
        avatar: '/images/avatars/profile-img-03.png'
      },
      {
        isActive: false,
        isChild: false,
        name: 'Fred',
        avatar: '/images/avatars/profile-img-01.png'
      },
      {
        isActive: false,
        isChild: true,
        name: 'Dirk',
        avatar: '/images/avatars/profile-img-02.png'
      },
    ]
  }
  
   handleSelect(i) {
      let rawAccountsData = this.state.accounts;
      rawAccountsData = rawAccountsData.map((val, index) =>       {
          val.isActive = index == i ? true : false;
          return val;
      });
      this.setState({
          accounts: rawAccountsData
      });
  }

  render() {
    const listAccounts = this.state.accounts;
    return (
      <div className="whos-watching-wrap container">
          <ProfileHeader />
          <h1>Who's Watching?</h1>
          <span>Select an account or add a new profile</span>
          <ListAccounts accounts={listAccounts}  handleSelect = {this.handleSelect.bind(this)} />
          <div className="whos-watching-cta">
            <button>Add Profile</button>
          </div>
      </div>
    );
  }
};

import React, {
    Component
} from 'react';
import PropTypes from 'prop-types';
import KidsIcon from '../../assets/svg/icons/kids.svg';

import './index.css';

export default class ListAccounts extends Component {

    constructor(props) {
        super(props);
        this.state = {
            accounts: props.accounts
        }
    }
    componentWillReceiveProps(props, state) {
        if (JSON.stringify(props.accounts) != JSON.stringify(state.accounts))
            this.setState({
                accounts: props.accounts
            });
    }
  
   render() {
        const { accounts,handleSelect } = this.props;
        return (
            <div className="list-accounts-wrap">
                {accounts.map((item, i) => {
                    return <div className="list-accounts-item is-selected" onClick={() => handleSelect(i)} key={i}>
                        <img src={item.avatar} />
                        <div className="account-details-wrap">
                            <span className="account-name">{item.name}</span>
                            {item.isChild == true ? <KidsIcon /> : null }
                        </div>
                    </div>
                })}             
            </div>
        )
    }

}

【讨论】:

  • 感谢您的回答,我认为组件中缺少函数handleSelect?
  • 糟糕! onClick={() =&gt; this.handleSelect(i)} 替换为 onClick={() =&gt; handleSelect(i)}
  • handleSelect 不是一个函数 - 超级奇怪,因为我看到你通过容器上的道具传递它。
  • 是的,这里也一样,您在控制台中遇到的任何其他错误?你能把console.log(handleSelect)放在render(){里面吗
  • 在第一个 sn-p 中更新了检查 handleSelect 函数。
【解决方案2】:

容器

import React, { Component } from 'react';
import { connect } from 'react-redux';
import './index.css'; // styles from

import ProfileHeader from '../../../components/ProfileHeader';
import ListAccounts from '../../../components/ListAccounts';

import { fetchingPageData } from '../../../actions';


class WhosWatching extends Component {
  state = {
    accounts: [
      {
        isActive: false,
        isChild: false,
        name: 'Olivia',
        avatar: '/images/avatars/profile-img-03.png'
      },
      {
        isActive: false,
        isChild: false,
        name: 'Fred',
        avatar: '/images/avatars/profile-img-01.png'
      },
      {
        isActive: false,
        isChild: true,
        name: 'Dirk',
        avatar: '/images/avatars/profile-img-02.png'
      },
    ]
  }

  toggle = (i) => {
    const accounts = [...this.state.accounts]
    accounts[i].isActive = !accounts[i].isActive
    this.setState({ accounts })
  }

  render() {
    const listAccounts = this.state.accounts;
    return (
      <div className="whos-watching-wrap container">
          <ProfileHeader />
          <h1>Who's Watching?</h1>
          <span>Select an account or add a new profile</span>
          <ListAccounts toggle={this.toggle} accounts={listAccounts} />
          <div className="whos-watching-cta">
            <button>Add Profile</button>
          </div>
      </div>
    );
  }
};

列出帐户

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import KidsIcon from '../../assets/svg/icons/kids.svg';

import './index.css';

export default class ListAccounts extends Component { 

    state = {
      accounts: []
    }

    componentDidMount(){
      const { accounts } = this.props;
      this.setState({ accounts })
    }

    componentWillReceiveProps(nextProps){
      if(nextProps.accounts){
        this.setState({ accounts })
      }
    }

    isSelected(index) {
      this.props.toggle(index)
    }

    render() {
        const { accounts } = this.state
        return (
            <div className="list-accounts-wrap">
                {accounts.map((item, i) => {
                    return <div className="list-accounts-item is-selected" onClick={() => this.isSelected(i)} key={i}>
                        <img src={item.avatar} />
                        <div className="account-details-wrap">
                            <span className="account-name">{item.name}</span>
                            {item.isChild == true ? <KidsIcon /> : null }
                        </div>
                    </div>
                })}             
            </div>
        )
    }

}

【讨论】:

  • 感谢您的帮助!我收到有关帐户在组件中未定义以及在 WhosWatching 容器中“i”未定义的错误。
猜你喜欢
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
相关资源
最近更新 更多