点击链接滚动到特定部分react.js

时间:2017-09-12 15:27:17

标签: javascript reactjs routes react-router

我已经实现了一个侧面菜单,每个部分都有一个链接标记,但我不确定如何在单击它们时实现该功能,用户将被带到特定部分。我理解如果它是在同一个组件中如何做,如果我以正常方式生成这些部分但我以不同的方式进行,我不确定如何实现像react-scroll或scrollchor这样的东西。 / p>

这里我通过映射我在另一个文件中的一些数据来生成包含buildTree的部分。

export default class CheckboxGroup extends PureComponent {
  constructor(props) {
    super(props);
    this.checkboxState = new Map();
    this.state = {
      checkboxState: new Map(),
    };
  }

  static propTypes = {
    data: PropTypes.any.isRequired,
    onChange: PropTypes.func.isRequired,
    counter: PropTypes.number,
  };

  treeCheckboxOnChange = (parentLabel, id, checked) => {
    this.checkboxState = this.checkboxState.setIn([parentLabel, id], checked);
    this.setState({
      checkboxState: this.checkboxState,
    });
  };

  mapParents = (counter, child) => {
    const parentLabel = child.get('label');
    return (
      <li key={child.get('name')} className='field'>
      <SegmentHeader style={segmentStyle} title={child.get('label')} icon={child.get('icon')}>
        <div className='fields' style={zeroMargin}>
          <div className='four wide field'>
            <TreeCheckbox
              label={`Grant ${child.get('label')} Permissions`}
              parentLabel={parentLabel}
              counter={counter}
              onChange={this.treeCheckboxOnChange}
            />
            {child.get('items') && this.buildTree(child.get('items'), counter + child.get('name'), parentLabel)}
          </div>
          <div className='twelve wide field'>
            <GrantDropdown checkboxState={this.state.checkboxState.get(parentLabel, new Map())} label={child.get('label')} childItems={child.get('items')}/>
          </div>
        </div>
      </SegmentHeader>
    </li>
    );
  };

  mapDataArr = (counter, parentLabel) => (child) => (
    (counter === 0) ?
      this.mapParents(counter, child)
      :
      <li key={child.get('name')}>
        <TreeCheckbox label={child.get('label')} parentLabel={parentLabel} onChange={this.treeCheckboxOnChange}/>
        {child.get('items') && this.buildTree(child.get('items'), counter + child.get('name'), parentLabel)}
      </li>
  )

  buildTree = (dataArr, counter, parentLabel) => (
    <ul key={counter} style={listStyle}>
      {dataArr.map(this.mapDataArr(counter, parentLabel))}
    </ul>
  )

  render() {
    return (
      <div className='tree-view'>
        {this.buildTree(this.props.data, this.props.counter)}
      </div>
    );
  }
}

我使用相同的技术来映射数据以创建我的粘性sideNav。

export default class SideNav extends Component {

  static propTypes = {
    data: PropTypes.any.isRequired,
    counter: PropTypes.number,
  };

  mapPermissionNames = (counter, child) => (
    <li key={child.get('name')}>
      <Link>{child.get('label')}</Link>
    </li>
  )

  mapDataArr = (counter) => (child) => (
    (counter === 0) ?
      this.mapPermissionNames(counter, child)
      :
      <li key={child.get('name')}>
        <Link>{child.get('label')}</Link>
      </li>
  )

  buildTree = (dataArr, counter) => (
    <ul key={counter} style={listStyle}>
      {dataArr.map(this.mapDataArr(counter))}
    </ul>
  )

  render() {
    return (
      <div className='tree-view'>
        {this.buildTree(this.props.data, this.props.counter)}
      </div>
    );
  }
}

这是他们两个都被渲染的父级。

export default class LocationPermissions extends AbstractSettingsComponent {

  handlePermissionChange = (e, { value }) => {
    this.updatePerson('locationPermissions', value);
  }

  updateCheckmarks = (id, checked) => {
    const { currentPerson } = this.props;
    if (checked && !currentPerson.get('permissions').includes(id)) {
      this.updatePerson('permissions', id, true);
    } else if (!checked && currentPerson.get('permissions').includes(id)) {
      this.filterItem(['currentPerson', 'permissions'], id, 1);
    }
  }

  render() {
    const { currentPerson } = this.props;
    return (
      <div>
        <SegmentHeader icon='building' title='Location Permissions'>
          <div className='two fields' style={zeroMarginBottom}>
            <div className='field'>
              <OptionSelector
                label={`Grant ${this.getPerson()} permissions for...`}
                options={this.getPermissionOptions()}
                value={currentPerson.get('locationPermissions') || 0}
                onChange={this.handlePermissionChange}
              />
            </div>
            {currentPerson.get('locationPermissions') === 2 &&
              <div className='field'>
                <label>Grant Location Admin Permissions For</label>
                <LocationMultiSelect name='Every' {...this.props}/>
              </div>
            }
          </div>
        </SegmentHeader>
        <StickyContainer>
        {currentPerson.get('locationPermissions') === 3 &&
          <div className='fields'>
            <div className='three wide field'>
              <Sticky style={{ paddingTop: '15px' }}>
                <SideNav
                  data={permissionSections}
                  counter={0}
                />
              </Sticky>
            </div>
            <div className='twelve wide field'>
            <CheckboxGroup
              data={permissionSections}
              counter={0}
              onChange={this.updateCheckmarks}
            />
          </div>
        </div>
        }
        </StickyContainer>
      </div>
    );
  }
}

我无法理解如何实现像react-scroll或scrollchor或react-router链接标记之类的东西,以便能够点击该部分并滚动到页面上的该部分。任何建议都会非常受欢迎。

3 个答案:

答案 0 :(得分:0)

我能够通过以下方式使用浏览器支持的方式:

<a href={`#${child.get('label')}`}>{child.get('label')}</a>

然后只需在列表元素中添加一个id。

答案 1 :(得分:0)

以这种方式正常工作(反应式js)

var str = "Mr Blue has a blue house and a blue car.";
let arr = ['blue','house','car']

var res = str.split(/\b/).reduce( (op,inp) => {
  if( !arr.includes(inp) ){
    op += inp.toUpperCase()
  } else {
    op += inp
  }
  return op
},'')
console.log(res.trim());

和其他页面上放置了一个id名称

id={'section1'}

答案 2 :(得分:0)

这是我在没有复杂步骤或没有第三方库的情况下所做的

1-创建一个带有onClick事件的div,然后添加window.location.replace以将当前URL替换为所需的URL。这是一个例子

<div onClick={() => window.location.replace("/#about")}>
<span>go to about</span>
</div>

2-在您的部分中添加您要使用的ID。

<h2 id="about">About</h2>

,并且所有操作都无需第三方库。欢呼。