小编A7D*_*7DC的帖子

您不应该在<Router>之外使用<Link>

我正在尝试在示例应用程序中设置react-router,我收到以下错误:

You should not use <Link> outside a <Router>
Run Code Online (Sandbox Code Playgroud)

我的应用程序设置如下:

父组件

const router = (
  <div className="sans-serif">
    <Router histpry={browserHistory}>
      <Route path="/" component={Main}>
        <IndexRoute component={PhotoGrid}></IndexRoute>
        <Route path="/view/:postId" component={Single}></Route>
      </Route>
    </Router>
  </div>
);

render(<Main />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

儿童/ Main组件

export default () => (
  <div>
    <h1>
      <Link to="/">Redux example</Link>
    </h1>
  </div>
)
Run Code Online (Sandbox Code Playgroud)

知道我在这里做错了吗?

这是一个用于演示问题的Sandbox链接.

jsx reactjs react-router

44
推荐指数
5
解决办法
5万
查看次数

使用 react-select 设置默认值不起作用

我有一个简单的 React 组件,它获得一个初始状态:

this.state = {
  currentObject: {
    isYounger: false
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我react-select用默认值渲染 a this.state.currentObject.isYounger

    <Select
      name={"age"}
      value={this.state.currentObject.isYounger}
      onChange={newValue => this.addIsYoungerValue(newValue)}
      options={isYoungerOptions}
    />
Run Code Online (Sandbox Code Playgroud)

由于某种原因,该值未设置。为什么是这样?

代码沙盒

版本:

"react-select": "^2.4.2",

javascript arrays reactjs react-select

10
推荐指数
3
解决办法
2万
查看次数

React JS 范围滑块 - 使用数组作为值?

我想知道您将如何使用 React 中的方法获取数组中索引的值input[type="range"],类似于此示例

我想做的是:传入一系列值,并能够使用数组的索引打印出这些值。

正如您将从下面的示例代码中看到的,我最初渲染我想要的值(在本例中为“Apples”),但是当我使用幻灯片时,它开始渲染数组的索引,而不是值。

这是我到目前为止所得到的:

class RangeSlider extends React.Component {
  // constructor
  constructor(props) {
    super(props);
    this.state = {
      value: props.value[0]
    };
  }

  handleChange(event, index) {
    const { value } = this.state;
    this.setState({ value: event.target.value});
  }

  render() {
    const { value } = this.state;
    const { label } = this.props;

    return (
      <div className="mb4">
        <label className="f4 mt0">
          {label} <b className="fw7 pl1">{value}</b>
        </label>
        <input
          className="w-100 appearance-none bg-transparent range-slider-thumb-custom"
          type="range"
          min={0}
          max={this.props.value.length - 1}
          step={1}
          value={value}
          onChange={this.handleChange.bind(this)}
        /> …
Run Code Online (Sandbox Code Playgroud)

javascript arrays range reactjs

5
推荐指数
1
解决办法
4737
查看次数

如何在 React 的 .map() 函数中切换单个元素的 css 类

我有一个 .map() 函数,我在其中迭代数组和渲染元素,如下所示:

      {options.map((option, i) => (
        <TachyonsSimpleSelectOption
          options={options[i]}
          key={i}
          onClick={() => this.isSelected(i)}
          selected={this.toggleStyles("item")}
        />
Run Code Online (Sandbox Code Playgroud)

我正在切换所选元素的状态,如下所示:

isSelected (i) {
    this.setState({ selected: !this.state.selected }, () => { console.log(this.state.selected) })
}
Run Code Online (Sandbox Code Playgroud)

使用 switch 语句更改样式:

  toggleStyles(el) {
    switch (el) {
      case "item":
        return this.state.selected ? "bg-light-gray" : "";
        break;
    }
  }
Run Code Online (Sandbox Code Playgroud)

然后在我的toggleStyles方法中将它作为道具传递给TachyonsSimpleSelectOption组件的 className 。

问题

该类正在为数组中的所有项目切换,但我只想定位当前单击的项目。

链接到沙盒。

我在这里做错了什么?

javascript dictionary reactjs

5
推荐指数
1
解决办法
4499
查看次数

在componentWillUpdate或componentDidUpdate内部重复调用setState吗?

我试图弄清楚作为组件传递的React组件中背景图像的方向。

我首先创建一个Image对象并将其src设置为新Image:

  getImage() {
    const src = this.props.url;
    const image = new Image();
    image.src = src;

    this.setState({
      height: image.height,
      width: image.width
    });
  }
Run Code Online (Sandbox Code Playgroud)

在使用高度和宽度更新状态后,我尝试getOrientation()在内部调用componentDidUpdate()

  getOrientation() {
    const { height, width } = this.state;
    if (height > width) {
      this.setState({ orientation: "portrait" });
    } else {
      this.setState({ orientation: "landscape" });
    }
  }
Run Code Online (Sandbox Code Playgroud)

然后,我得到以下错误:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

链接到沙盒

javascript image orientation setstate reactjs

5
推荐指数
1
解决办法
3342
查看次数

你如何获得一个孩子的无状态功能组件的高度?

我正在尝试获取无状态子组件的高度,以便我能够在父类中使用它的高度,但是我收到以下错误: Invariant Violation: Stateless function components cannot have refs.

简化代码

家长班

class App extends React.Component {
  componentDidMount() {
    console.log(this.header);
  }
  render() {
    return (
      <Child ref={component => this.header = component} />
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

儿童

const Child = () => (
  <header ref="header">
    Some text  
  </header>
)
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

这是一个带错误的Codepen链接.

更新:

实际代码/上下文

所以我目前有一个Header组件,看起来像这样:

export const Header = ({dateDetailsButton, title, logo, backButton, signUpButton, inboxButton, header}) => (
    <header header className="flex flex-row tc pa3 bb b--light-gray relative min-h-35 max-h-35">
      {signUpButton ? …
Run Code Online (Sandbox Code Playgroud)

components stateless refs reactjs

4
推荐指数
1
解决办法
2685
查看次数

在 SCSS 中使用 Storybook/vue

我使用创建了一个项目vue create,然后安装了 Storybook。它运行良好,除非我向组件添加 scss 时出现以下错误:

Module parse failed: Unexpected token (14:0)
File was processed with these loaders:
 * ./node_modules/vue-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| 
| 
> .test {
|   background: red !important;
| }
Run Code Online (Sandbox Code Playgroud)

这是我的组件的样子:

<template>
    <h1 class="test">Hello</h1>
</template>

<script>
export default {
  name: "Test",
    props: {
        msg: String
    },
}
</script>
<style lang="scss" scoped>
  .test {
    background: red !important;
  }
</style>
Run Code Online (Sandbox Code Playgroud)

如果我删除<style>标签,错误就会消失。

我已按照此处的文档添加sass …

javascript css sass vue.js storybook

4
推荐指数
2
解决办法
4979
查看次数

使用自定义组件时不会触发 onChange 处理程序

我在 React 应用程序中使用Formik进行验证。

验证工作正常,但我的 onChange 处理程序没有触发:

  <Field
    type="text"
    name="name"
    placeholder="First Name"
    component={Input}
    onChange={() => console.log("gfdg")}
  />
Run Code Online (Sandbox Code Playgroud)

沙盒链接

为什么是这样?

javascript forms onchange reactjs formik

3
推荐指数
1
解决办法
8071
查看次数

SVG笔画未显示在clipPath内部

我有以下Codepen,我试图在其中为图像周围的圆圈设置动画。

到目前为止,我有一个圆形 SVG 正在剪辑图像,但它没有显示 clipPath 内部的笔划。

如何让边框显示?

class App extends React.Component {
  render() {
    return (
      <svg width='48' height='48'>
        <defs>
          <clipPath id='circleView'>
            <circle cx='24' cy='24' r='23' fill='none' stroke='red' strokeWidth='2' />
          </clipPath>
        </defs>
        <image width='48' height='48' xlinkHref={'https://source.unsplash.com/random'} clipPath='url(#circleView)' />
      </svg>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

svg border stroke reactjs

2
推荐指数
1
解决办法
1050
查看次数

如何在React JS中的对象内的数组上进行迭代

想象一下,我有一个像这样的对象数组:

const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]
Run Code Online (Sandbox Code Playgroud)

我想将images数组中的每个图像分配给CarrouselItem使用props 调用的React组件:

class CarrouselItem extends React.Component {
  render() {

    return (
      <div>
        <img src={this.props.imageUrl} />
      </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

然后将其放置在称为的父组件中Carrousel,在该对象上循环遍历该对象并返回内部的图像,以将其放置在该CarrouselItem组件内部:

class Carrousel extends React.Component {
  render() {
    return (
      <div>
        <h4>Slide image</h4>
        {chefs.map((chef, index) => {
          return <CarrouselItem imageUrl={chef.images[index]} />
        })}
      </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

我期望发生什么

map函数应该遍历所有对象(在这种情况下,只是其中的一个),然后创建X个CarrouselItem组件,每个组件都<img>images数组中获取一个。

实际发生了什么

不幸的是,我只得到数组中的第一项(在本例中为'http://lorempixel.com/400/400/sports/' …

javascript arrays object reactjs

1
推荐指数
1
解决办法
2623
查看次数

如何通过单个反应选择正确使用 Yup 模式?

我正在使用react-selectwithFormikYup来验证我的表单,但由于某种原因我的验证不起作用。我的架构如下所示:

const Schema = Yup.object().shape({
age: Yup.object().shape({
    label: Yup.string().required("Required"),
    value: Yup.string().required("Required")
})
});
Run Code Online (Sandbox Code Playgroud)

我的数据如下所示:

export const ageOptions = [
  { value: 0.1, label: "Not born yet" },
  { value: 0.3, label: "Baby - 0 to 3 months" },
  { value: 0.6, label: "Baby - 3 to 6 months" },
  { value: 0.12, label: "Baby - 6 to 12 months" },
  { value: 0.18, label: "Baby - 12 to 18 months" },
  { value: 0.24, …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-select yup formik

1
推荐指数
1
解决办法
8211
查看次数

在数组中查找对象?

想象一下,我有一个这样的对象数组(虚拟代码):

const chosenBets = [{...}, {...}] // 2 items
Run Code Online (Sandbox Code Playgroud)

我想从数组中删除特定项目:

{id: 0, // is unique
 label: 1,
 odd: 1.33,
 oddIndex: 0,
 team_home: "Liverpool",
 team_away: "Sheffield United",
 matchCardIndex: 0,}
Run Code Online (Sandbox Code Playgroud)

现在该数组为:

const chosenBets = [{...}] // 1 items
Run Code Online (Sandbox Code Playgroud)

我将如何实现?

javascript arrays object reactjs

1
推荐指数
1
解决办法
47
查看次数

为什么 React 中索引显示 [object Object] 而不是整数?

我已经有一段时间没有使用 React,但我遇到了一个问题。

当我在地图函数中 console.log 我的索引时,我的控制台向我显示:

在此输入图像描述

但随后我的浏览器中的结果显示:

[对象对象]1 在此输入图像描述

我希望它显示索引+1,所以第一个是1,第二个是2,第三个是3,依此类推。这是我的代码:

import React from "react";
import Container from '../Container'
import content from '../../content/landing'

function Step(index: any) {
    return (
        <div className="rounded-full h-12 w-12 bg-yellow border-4 border-black">
            {index + 1}
        </div>
    )
}

function HowItWorks() {

    const listItems = content?.howto?.map((c:any, index:any) => {
        console.log(index, 'index')
        return (
            <div className="mb-12 filter-none shadow-1 bg-white p-4 py-8 rounded-lg border-4 border-black" key={index}>
                <Step index={index}/>
                <h3 className="text-xl font-bold">{c.title}</h3>
                <p className="text-xl">{c.text}</p>
            </div>
        )
    }

    );
    return (
      <div className="bg-purple-600 py-12"> …
Run Code Online (Sandbox Code Playgroud)

javascript loops typescript reactjs next.js

-1
推荐指数
1
解决办法
154
查看次数