标签: react-props

React 中的“道具”究竟是什么?

我刚开始在 iOS 上使用 React native 看看感觉如何,我有一个愚蠢的问题.. 我看到每个人都在谈论“道具”,每当我阅读文章或教程时,作者经常使用这个术语,它是代码中相同。例如,在类声明中,我经常看到像这样的构造函数:

class MyClass extends Component {

    constructor(props) {
        super(props);
        this.state = { message: '' };
    }
}
Run Code Online (Sandbox Code Playgroud)

我找不到关于道具是什么的明确解释,有人可以启发我吗?

reactjs react-native react-props

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

React:从 ParentComponent 中的子级获取原始 jsx

是否有可能获得jsxParent组件包装的实际“原始”文本(例如 from props.children)?

鉴于此组件:

<Parent>
    <Child name={'test'} />
</Parent>
Run Code Online (Sandbox Code Playgroud)

题:

Parent.js,我可以用this.props.children(或其他任何东西)做任何事情来得到这个(最好是一个字符串):

输出:

"<Child name={'test'} />"

jsx reactjs babeljs react-props

5
推荐指数
0
解决办法
124
查看次数

onclick 道具不适用于 Material UI?

这是我在 React.js 上的情况

我的 App.js 调用 selectNumberOfPeople 上有一个函数,

然后在我的子组件(调用 General)中,我有一个按钮:

<button className="selectedNumberOfPeopleButton" onClick={this.selectedNumberOfPeople} value="1">
      1
</button>
Run Code Online (Sandbox Code Playgroud)

单击时在控制台中显示值。

完美运行。

我现在想改用 Material UI 中的按钮,因此我将按钮替换为:

<RaisedButton className="selectedNumberOfPeopleButton" 
    onClick={this.props.selectedNumberOfPeople}
    value="1" 
    label="1" 
    labelPosition="before"
    primary={true}
/>
Run Code Online (Sandbox Code Playgroud)

但是在使用 this 时,控制台中不再显示该值。. .

虽然函数在父组件中,但我确实通过了它:

<General selectNumberOfPeople={this.selectNumberOfPeople} selectedPanel={this.showPanelAndHideOthers} />
Run Code Online (Sandbox Code Playgroud)

我尝试更新我的子组件(General.js),例如:

<RaisedButton selectNumberOfPeople={this.props.selectNumberOfPeople}
    className="selectedNumberOfPeopleButton" 
    onClick={this.props.selectedNumberOfPeople}
    value="1" 
    label="1" 
    labelPosition="before"
    primary={true}
/>
Run Code Online (Sandbox Code Playgroud)

但它仍然无法正常工作......

供您参考,

selectNumberOfPeople 在 App.js 中作为

selectNumberOfPeople(value) {
console.log('select number of people');
// update the state and provide a callback handler to be called after the state is updated.
// referencing …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-props

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

在使用中反应钩子道具

我已经开始使用react-hooks并且有一些我想了解的东西。我有这个useEffect钩子,我正在分离useEffect钩子,我想知道每个钩子何时运行。

function MyComp(props) {
    useEffect(
       () => {
         fetchSomeData(props.filters)
       },[props.filters]
     )
    return (
        <div>will show my data here</div>
     )
}
Run Code Online (Sandbox Code Playgroud)

此挂钩是否仅在props.filters更改后才运行?

还是我必须使用prevProps检查它是否已更改?

像这样:

function MyComp(props) {
   const prevProps = useRef(props);
   useEffect(
       () => {
           if (prevProps.filters !== props.filters) {            
              fetchSomeData(props.filters)
           }
       },[props.filters]
   )
   return (
     <div>will show my data here</div>
   )
}
Run Code Online (Sandbox Code Playgroud)

reactjs react-props react-hooks

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

当我更改在 React 中传递给它的道具时,组件不会更新

我有一个具有子组件的功能组件。子组件显示一些通过 props 从父组件传递给它的文本。当我更改父组件中的文本并将其向下传递时,子组件仍保留旧文本。

下面是父组件 MainPage 的最小可重现示例。

function MainPage(){
    let text = "This is the original text";
    setTimeout(function(){ text = "This is the new text" }, 3000);
    return(<DisplayText text={text} />);
}
Run Code Online (Sandbox Code Playgroud)

下面是显示文本。

function DisplayText(props){
    return(<p>{props.text}</p>)
}
Run Code Online (Sandbox Code Playgroud)

如何更新子组件,使其在 3 秒后显示“这是新文本”而不​​是“这是原始文本”?

提前致谢!

javascript parent-child rerender reactjs react-props

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

getInitialProps 不适用于异步函数

我在这个路径中有文件,./pages/blog/[id]/[title].js这里是我写的代码:

import React from 'react';
import PropTypes from 'prop-types';
import fetch from 'isomorphic-unfetch';
import BASE_URL from '../../../BaseURL';


const BlogSinglePage = props => {
  console.log(props.post);//undefined
  console.log(props);//{}
 return (
   <div></div>
 );
};

BlogSinglePage.propTypes = {
  post: PropTypes.object
};

BlogSinglePage.getInitialProps = async ({ query }) => {
    const res = await fetch(`${BASE_URL}/api/post/${query.id}`);
    const post = await res.json();
    return { post };
};

export default BlogSinglePage;
Run Code Online (Sandbox Code Playgroud)

我的问题是什么时候getInitialProps 是一个async函数,它BlogSinglePage的 props 是空的,但是当getInitialProps 它不是一个async函数时,一切正常,props 不是空的

我已按照逐行实现帖子页面中 …

javascript reactjs next.js react-props

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

使用链接 React-Bootstrap 控制轮播

我正在尝试从导航栏中的链接控制轮播。我现在拥有的是 HomePage 组件(NavBar 和 Carousel 的父组件)中的 click 方法,它根据在 NavBar 中单击的链接更新当前选定索引的状态。我对如何让 Carousel 收听索引状态并在按下 Link 后移动幻灯片的方法一无所知。当我最初设置 activeIndex 时,我无法让它正确收听作为道具传递的索引,并且 onSelect 处理程序也基本上什么都不做。

更新:HomePage => 刚刚向状态添加了方向以反映下面轮播中更新 v2 的变化。

class HomePage extends Component {
    constructor(props){
        super(props);
        this.state = {index: '0', direction: null};
    }

    handleclick = (i) => {
        this.setState({direction: (this.state.index>i) ? 'prev':'next', index: i});
    }

    render() {
        return (
            <Container className='containerCustom d-flex h-100 w-100' fluid>
                <Row className='fullscreen-bg h-100 w-100'>
                    <video loop autoPlay className='fullscreen-bg_video w-100 h-100'>   
                        <source src={background} type='video/mp4'/>
                    </video>
                </Row>
                <Row className='flex-fill w-100 navrow' noGutters>
                    <Col …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-bootstrap react-props controlled-component

5
推荐指数
0
解决办法
976
查看次数

如何使用道具字符串将值传递给StaticQuery?

我正在 Gatsby.js 中开发一个网站,其中包含一个博客并用于帖子布局,我正在使用由帖子作者设置的背景图像对这个标题进行编码。我仍处于设计阶段,放置元素,空白文本等。

我已经使用 BackgroundImage、graphQL 和 StaticQuery 制作了这个组件,并且在它的代码中,如果我用“post_8.jpg”文本缩小对来自 gatsby-source-filesystem 的图像的搜索范围,它应该可以正常工作。

import React from 'react'
import { graphql, StaticQuery } from 'gatsby'
import BackgroundImage from 'gatsby-background-image'
import TextScramble from './TextScramble'


const BackgroundDiv = ({ className, children }) => (
  <StaticQuery 
    query={graphql`
      query($post: String! ) {
        file(relativePath: {eq: "post_8.jpg"}) {
          childImageSharp {
            fluid {
              ...GatsbyImageSharpFluid
            }
          }
        }
        }
      `
    }
    render={data => {
      const imageData = data.file.childImageSharp.fluid
      return (
        <BackgroundImage
          Tag="div"
          className={className}
          fluid={imageData}
        >
    <h1 className="bg-white shaddow shadow-md py-1 px-4 w-auto …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs graphql gatsby react-props

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

从数据库获取后如何传递道具?

我用作Firebase后端,架构如下

const sample_data = {
  Name: "",
  Address: "",
  Contact_no: "",
  Email: "",
  img_url: ""
}
Run Code Online (Sandbox Code Playgroud)

首先我用async这样的函数来获取

FetchList.js


let dummy = {}

async function getItems(){
    const response = await fetch('realtime__database__of__firebase__url');
    
    if (!response.ok) {
        throw new Error("Something went wrong");
      }
  
      dummy = await response.json();
}
getItems();
export default dummy;
Run Code Online (Sandbox Code Playgroud)

然后我将检索到的数据传递到我的组件,如下所示。

ListHospital.js

import Card from "../UI/Card";
import dummy from "./FetchList";


const ListHospitals = () => {
    return <Card>
        {dummy}
    </Card>
}

export default ListHospitals;
Run Code Online (Sandbox Code Playgroud)

最后,我想访问我在CARD …

javascript async-await reactjs react-props

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

使用变量时 Tailwind 不起作用(React.js)

目前使用顺风并制作可重用的反应组件面临着这个问题,您可以将一些样式作为顺风类作为道具传递。实际的问题在于“pb-{number}”属性。我可以通过这种方式,并且会很好地工作。“border-{number}”属性也会发生这种情况,但不知何故它接受 border-2 和 border-4 (仅限这些)。

import './button.css'
    
    export default function Button({
        color = "orange",
        inset = "pb-3", <--- this will work
        border = "border-8",
        className, 
        onClick, 
        link
        , ...props}){
        
        return (
            <div onClick={onClick}
            className={`btn-${color} ${border} 
            ${className} ${inset}`}> <--- this will work
                
                <div>
                    {props.children}
                </div>
            </div>
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试使其更清晰,那么不使用顺风的人只需传递一个值(如下例所示),它将无法工作。

import './button.css'

export default function Button({
    color = "orange",
    inset = "1", <--- this
    border = "4",
    className, 
    onClick, 
    link
    , ...props}){
    
    return (
        <div onClick={onClick}
        className={`btn-${color} border-${border} 
        ${className} pb-${inset}`}> <--- this wont work …
Run Code Online (Sandbox Code Playgroud)

default-parameters reactjs react-props tailwind-css

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